简体   繁体   中英

HttpClient Download Image From URL Then Upload Image

I have an image that sits in a url.

https://somecdn/content/myimage.png

I want to pass this string to my API,Download the image into memory then upload to another API.

I'm using an api client that is generated from our swagger that takes a type of IO.stream.

Code is as follows.

    public async Task<int> UploadPicture(string fileUrl)
    {
        
        var otherApiClient = await _otherApiClient.Build();
        var fileRetrievalClient = new HttpClient();           

        var fileResponse = await fileRetrievalClient.GetAsync(fileUrl);
        

        var newId = await otherApiClient.UploadPictureAsync(file: await fileResponse.Content.ReadAsStreamAsync());

        return newId;
    }

Normally when this is called via the front end the types are set correctly correctly.

Content-Disposition: form-data; name="file"; filename="yadayada.png" Content-Type: image/png

However in my code the Content-Type is wrong.

Content-Type: application/octet-stream Content-Disposition: form-data; name=file; filename= unknown

How can I correct this.

you can do something like this:

var fileResponse = await fileRetrievalClient.GetAsync(fileUrl);
byte[] bytes = await fileResponse.Content.ReadAsByteArrayAsync();
using (var content = new ByteArrayContent(bytes))
{
    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    content.Headers.TryAddWithoutValidation("Content-Disposition", "application/octet-stream name=test");
    var postResponse = await otherApiClient.PostAsync(uri, content);
}

HttpClient doesn't have a method called UploadPictureAsync . This indicates that the Type of variable otherApiClient is not HttpClient .

You need to check what other parameters you can pass to UploadPictureAsync and see how you can pass custom headers using the values from fileResponse.Headers

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