[英]Convert HttpResponseMessage into byte array
我在将图像上传到服务器时遇到了一些麻烦
这是代码:
var uploadServer = api.Photo.GetUploadServer(123);
var c = new HttpClient();
var formData = new MultipartFormDataContent();
var requestContent = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(File.ReadAllBytes("images/amogus.jpg"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "amogus.jpg"
};
formData.Add(fileContent);
var responseFile = Encoding.ASCII.GetString(await c.PostAsync(uploadServer.UploadUrl, formData));
首先我得到了一个在那里上传图片的链接,然后我将图片添加到formData并尝试使用PostAync发送,在这一步我遇到了麻烦,因为PostAsync希望uploadUrl是byte [],但它是一个HttpResponseMessage。 我如何转换它?
这里还有错误信息:
参数 1:无法从 'System.Net.Http.HttpResponseMessage' 转换为 'byte[]'
您可以使用ReadAsStreamAsync
然后将其传递给StreamReader
以读取字符串。
您还缺少各种using
块,您也可以 stream 将您的文件直接放入ByteArrayContent
。 requestContent
似乎在这里没有使用。
static HttpClient c = new HttpClient(); // always keeps static or you could get socket exhaustion
using (var formData = new MultipartFormDataContent())
using (var fileContent = new StreamContent(File.Open("images/amogus.jpg", FileMode.Open, FileAccess.Read)))
{
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "amogus.jpg"
};
formData.Add(fileContent);
using (var response = await c.PostAsync(uploadServer.UploadUrl, formData))
using (var responseStream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(responseStream, Encoding.ASCII))
{
var yourString = await responseStream.ReadToEndAsync();
// do stuff with string
}
}
你确定你想要ASCII
而不是UTF8
吗? 如果是这样,您可以将整个事情缩短到这个
using (var formData = new MultipartFormDataContent())
using (var fileContent = new StreamContent(File.Open("images/amogus.jpg", FileMode.Open, FileAccess.Read)))
{
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "amogus.jpg"
};
formData.Add(fileContent);
using (var response = await c.PostAsync(uploadServer.UploadUrl, formData))
{
var yourString = await response.ReadAsStringAsync();
// do stuff with string
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.