gpt4 book ai didi

c# - 如何使用 Xamarin Form 将流形式的图像上传到多部分休息服务

转载 作者:太空宇宙 更新时间:2023-11-03 12:54:08 24 4
gpt4 key购买 nike

我正在使用这段代码,但发现 xamarin 中的 System.Net 没有定义 GetRequestStreamAsyncGetResponseAsync

那么将文件上传到服务器的替代方法是什么..

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;

}

最佳答案

阿比。

您可以使用 System.Net.Http 中的 HttpClient(我记得需要安装 NuGet 包)。简单的方法如下所示:

HttpClient client = new HttpClient();
ByteArrayContent content = new ByteArrayContent(yourBytesHere);
HttpResponseMessage response = await client.PostAsync(urlHere, content);

此外,如果您不仅需要发送文件,还需要发送其他一些数据,请使用 MultipartFormDataContent;

关于c# - 如何使用 Xamarin Form 将流形式的图像上传到多部分休息服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34543900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com