简体   繁体   中英

Upload image and string via HTTP POST windows phone 8.1 with HttpClient

I have a Windows Phone application in C#. I am trying send a image (byte[]) and a session token (string) to my django server, but not how to do it.

I 've looked at other post but it does not work what they do , or classes that use do not exist.

The header of my function is:

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


    }

EDITED: My problem now is my server don't get the image. The django code is:

     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']

I can't modify the django code because this code it's working with Android app

Using this response ,

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

Try with this...

        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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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