如何使用Xamarin form将流形式的图像上传到多部分休息服务
本文关键字:多部 服务 图像 form Xamarin 何使用 | 更新日期: 2023-09-27 18:28:32
我使用了这段代码,但发现xamarin中的System.Net没有GetRequestStreamAsync和GetResponseAsync的定义。
那么,将文件上传到服务器的另一种方式是什么呢。。
public static async Task<string> PostMultiPartForm(string url, byte[] file, string paramName, string contentType, Dictionary<String, string> nvc,
string cookie)
{
// log.Debug(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("'r'n--" + boundary + "'r'n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.Headers ["Cookie"] = cookie;
//wr.KeepAlive = true;
//wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = await wr.GetRequestStreamAsync();
string formdataTemplate = "Content-Disposition: form-data; name='"{0}'"'r'n'r'n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name='"{0}'"; filename='"{1}'"'r'nContent-Type: {2}'r'n'r'n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
rs.Write(file,0, file.Length);
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("'r'n--" + boundary + "--'r'n");
rs.Write(trailer, 0, trailer.Length);
//rs.Close();
string responseString = String.Empty;
WebResponse wresp = null;
try
{
wresp = await wr.GetResponseAsync();
Stream respStream = wresp.GetResponseStream();
StreamReader respReader = new StreamReader(respStream);
responseString = respReader.ReadToEnd();
//log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
//log.Error("Error uploading file", ex);
if (wresp != null)
{
//wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
return responseString;
}
Abhi。
您可以使用System.Net.Http中的HttpClient(我记得需要安装NuGet包)。简单的方法如下:
HttpClient client = new HttpClient();
ByteArrayContent content = new ByteArrayContent(yourBytesHere);
HttpResponseMessage response = await client.PostAsync(urlHere, content);
此外,如果您不仅需要发送文件,还需要发送其他一些数据,请使用MultipartFormDataContent;