【问题标题】:HttpClient Download Image From URL Then Upload ImageHttpClient 从 URL 下载图片然后上传图片
【发布时间】:2020-12-18 19:02:22
【问题描述】:

我有一个位于 url 中的图像。

https://somecdn/content/myimage.png

我想将此字符串传递给我的 API,将图像下载到内存然后上传到另一个 API。

我正在使用一个 api 客户端,它是从我们的 swagger 生成的,它采用一种 IO.stream 类型。

代码如下:

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

通常当通过前端调用时,类型设置正确:

内容配置:表单数据;名称=“文件”;文件名="yadayada.png" 内容类型:image/png

但是在我的代码中 Content-Type 是错误的:

内容类型:application/octet-stream 内容处置:表单数据;名称=文件;文件名=未知

我该如何纠正这个问题?

【问题讨论】:

    标签: c# upload asp.net-core-webapi dotnet-httpclient


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      HttpClient 没有名为 UploadPictureAsync 的方法。这表明变量otherApiClientType不是HttpClient

      您需要检查可以传递给 UploadPictureAsync 的其他参数,并了解如何使用 fileResponse.Headers

      中的值传递自定义标头

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-30
        • 2015-09-15
        • 2021-03-10
        • 1970-01-01
        • 1970-01-01
        • 2012-09-19
        相关资源
        最近更新 更多