使用HttpClient通过HTTP POST Windows Phone 8.1上传图像和字符串

时间:2014-11-30 09:24:44

标签: c# django http post windows-phone-8

我在C#中有一个Windows Phone应用程序。我正在尝试将图像(byte [])和会话令牌(字符串)发送到我的django服务器,但不是如何做。

我查看过其他帖子,但它不起作用,或者使用的课程不存在。

我的功能标题是:

    public static async Task<bool> sendImagePerfil(string token, byte[] imagen)
    {
        using (var client = new HttpClient())
        {
            var values = new List<KeyValuePair<string, string>>();
            values.Add(new KeyValuePair<string, string>("token", token));
            values.Add(new KeyValuePair<string, string>("image", Convert.ToString(imagen)));

            var content = new FormUrlEncodedContent(values);

            var response = await client.PostAsync("MyURL.domain/function", content);

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


    }

已编辑:我现在的问题是我的服务器无法获取图像。 django代码是:

     if request.method == 'POST':
        form = RestrictedFileField(request.POST, request.FILES)
        token = models.UsuarioHasToken.objects.get(token=parameters['token'])
        user = token.user
        print (request.FILES['image'])
        user.image = request.FILES['image']

我无法修改django代码,因为此代码正在使用Android应用

1 个答案:

答案 0 :(得分:7)

使用此回复,

How to upload file to server with HTTP POST multipart/form-data

试试这个...

        HttpClient httpClient = new HttpClient();
        MultipartFormDataContent form = new MultipartFormDataContent();

        form.Add(new StringContent(token), "token");

        var imageForm = new ByteArrayContent(imagen, 0, imagen.Count());
        imagenForm.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");

        form.Add(imagenForm, "image", "nameholder.jpg");

        HttpResponseMessage response = await httpClient.PostAsync("your_url_here", form);

        response.EnsureSuccessStatusCode();
        httpClient.Dispose();
        string result = response.Content.ReadAsStringAsync().Result;