简体   繁体   中英

Convert HttpResponseMessage into byte array

i have some troubles with uploading image onto a server

here's the code:

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));

in the first i'm getting a link to upload image there, then i'm adding image to formData and trying to send with PostAync, on this step i have trouble because PostAsync wants uploadUrl to be byte[] but it is a HttpResponseMessage. how do i convert it?

also here is error message:

Argument 1: cannot convert from 'System.Net.Http.HttpResponseMessage' to 'byte[]'

You can use ReadAsStreamAsync and then pass it to a StreamReader to read the string.

You are also missing various using blocks, and you can also stream your file directly into ByteArrayContent . requestContent appears to be unused here.

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
    }
}

Are you sure you want ASCII and not UTF8 ? If so you could shorten the whole thing to this

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM