Search code examples
c#asp.net-web-apimultipartform-dataform-dataimage-upload

C# web api post image as form data


In postman it is easily done:

postman-using form-data image upload

In order to implement it by web api, i've written below code:

HttpClient client = new HttpClient();
string url = "https://upload.*******.com/api/upload/photos";
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Clear();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

byte[] data;
using (var br = new BinaryReader(inputPhotoUpload.files.OpenReadStream()))
data = br.ReadBytes((int) inputPhotoUpload.files.OpenReadStream().Length);

ByteArrayContent bytes = new ByteArrayContent(data);

MultipartFormDataContent multipartFormDataContent = new 
MultipartFormDataContent();
multipartFormDataContent.Add(new StringContent(inputPhotoUpload.watermark.ToString()), "watermark");
multipartFormDataContent.Add(new StringContent("listing"), "type");
multipartFormDataContent.Add(bytes, "files", inputPhotoUpload.files.FileName);

HttpResponseMessage res = await client.PostAsync(url, multipartFormDataContent);

my InputPhotoUpload class

public class InputPhotoUpload
{
    public string watermark { get; set; }
    public string type { get; set; }
    public IFormFile files { get; set; }
}

The uploading server accepts and image in byte array and two other values named listing and watermark. the server gives code 500 internal error. My goal is to post a form-data post to upload an image, post man is able to do it yet my controller api cannot.


Solution

  • apparently i needed to sync all headers with postman, some were unnecessary.

     HttpClient client = new HttpClient();
                    MultipartFormDataContent form = new MultipartFormDataContent();
                    client.DefaultRequestHeaders.Clear();         
    
                    ByteArrayContent bytes = new ByteArrayContent(imageStream);
                    form.Add(bytes, "files", imageName);
                    form.Add(new StringContent("En"), "watermark");
                    form.Add(new StringContent("listing"), "type");
    
    
                    HttpResponseMessage response = await client.PostAsync("https://upload.*****.com/api/upload/photos", form);
                    var k = response.Content.ReadAsStringAsync().Result;
    
                    _Result = JsonConvert.DeserializeObject<List<Output>>(k);