简体   繁体   English

HttpClient从URL下载图片然后上传图片

[英]HttpClient Download Image From URL Then Upload Image

I have an image that sits in a url.我有一个位于 url 中的图像。

https://somecdn/content/myimage.png https://somecdn/content/myimage.png

I want to pass this string to my API,Download the image into memory then upload to another API.我想将此字符串传递给我的 API,将图像下载到 memory 然后上传到另一个 API。

I'm using an api client that is generated from our swagger that takes a type of IO.stream.我正在使用从我们的 swagger 生成的 api 客户端,它采用 IO.ZF7B44B44CAFFD5C58A72E7D 类型

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 filename="yadayada.png" 内容类型:image/png

However in my code the Content-Type is wrong.但是在我的代码中,Content-Type 是错误的。

Content-Type: application/octet-stream Content-Disposition: form-data; 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 . HttpClient没有名为UploadPictureAsync的方法。 This indicates that the Type of variable otherApiClient is not HttpClient .这表明变量otherApiClient类型不是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您需要检查可以传递给UploadPictureAsync的其他参数,并查看如何使用fileResponse.Headers中的值传递自定义标头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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