[英]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.