【问题标题】:How to send image in HttpClient SendRequestAsync如何在 HttpClient SendRequestAsync 中发送图像
【发布时间】:2015-11-04 00:37:49
【问题描述】:

我正在使用 Windows.Web.Http 而不是 System,并且我正在尝试发送图像。

我的示例代码:

    Dictionary<string, object> requestDictionary;
    HttpClient httpClient = new HttpClient();
    HttpRequestMessage re = new HttpRequestMessage();
    HttpResponseMessage response;
    re.Method =  HttpMethod.Post;
    re.RequestUri = url;
    string content_type = "application/json";
    string req_data = JsonConvert.SerializeObject(requestDictionary);

    re.Content = new HttpStringContent(req_data, UnicodeEncoding.Utf8, content_type);

    response = await httpClient.SendRequestAsync(re);
    response.EnsureSuccessStatusCode();

    var responseString = await response.Content.ReadAsStringAsync();

    httpClient.Dispose();
    httpClient=null;

在这种情况下,我的 requestDictionary 将类似于

    requestDictionary.Add("Image", filename);
    requestDictionary.Add("description", some_description);

请有人帮我实现这一目标。

【问题讨论】:

    标签: c# windows multipartform-data uwp


    【解决方案1】:

    通过使用 .Net 4.5(或通过从 NuGet 添加 Microsoft.Net.Http 包),有一种更简单的方法:

    private string Upload(string actionUrl, string paramString, byte[] paramFileBytes)
    {
        HttpContent stringContent = new StringContent(paramString);
        HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "paramter");
            formData.Add(bytesContent, "image");
            var response = client.PostAsync(actionUrl, formData).Result;
            if (!response.IsSuccessStatusCode)
            {
                return null;
            }
            return response.Content.ReadAsStringAsync().Result;
        }
    } 
    

    如果您更喜欢使用流而不是字节数组,您可以轻松做到这一点,只需使用new StreamContent() 而不是new ByteArrayContent()

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 2021-01-31
      • 2021-03-01
      • 1970-01-01
      • 2019-09-21
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多