Send image to WebApi service

前端 未结 2 1630
一生所求
一生所求 2021-01-24 04:34

I\'m making a project on Windows Phone where user can take a photo, save it on phone and next upload on my server. So there are two projects, WP8.1 and ASP.NET WEB API.

2条回答
  •  春和景丽
    2021-01-24 04:58

    You need to use multipart/form-data request to the server. You can send the json to the web api using payload field (another alternative is send every field separately, but you need reflection to do that.)

    This maybe can help you:

    public string UploadUserPictureApiCommand(string api, string json, byte[] picture)
    {
        using (var httpClient = new HttpClient())
        {
    
           MultipartFormDataContent form = new MultipartFormDataContent();
    
           form.Add(new StringContent(json), "payload");
           form.Add(new ByteArrayContent(picture, 0, picture.Count()), "user_picture", "user_picture.jpg");
    
           HttpResponseMessage response = await httpClient.PostAsync(api, form);
    
           response.EnsureSuccessStatusCode();
    
           Task responseBody = response.Content.ReadAsStringAsync();
    
            if (response.StatusCode.ToString() != "OK")
            {
                return "ERROR: " + response.StatusCode.ToString();
            }
            else
            {
                return "SUCCES: " + responseBody.Result.ToString();
            }
        }
    }
    

提交回复
热议问题