1

我正在使用 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);

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

4

1 回答 1

2

通过使用 .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().

于 2015-08-11T17:11:33.557 回答