4

I'm following this blog post to upload an image using C# Web API.

The article explains how to do it using ARC and it works fine.

But when I'm trying to do the same using POSTMAN it's failing.

Here is my request snapshot.

enter image description here

enter image description here

RBT
  • 24,161
  • 21
  • 159
  • 240
Simsons
  • 12,295
  • 42
  • 153
  • 269

2 Answers2

7

TL;DR: You are doing everything correct except that you are setting the Content-Type header explicitly in the tool. Get rid of the header and your issue will be resolved.

Detailed Explanation: To begin with, you attach the files using form-data option in the Body tab in the tool:

enter image description here

The moment you select the file(s), Postman auto-detects the Content-Type. Then behind the scenes, Postman inserts the automatically detected Content-Type into the POST request without us knowing it. So setting up Content-Type header explicitly on our own messes up the request.

Setting the value of Content-Type header to multipart/form-data involves a complex concept of setting up boundaries of multiple parts of the file as detailed here. It can be error-prone. So heavy lifting of setting up the boundaries is done automatically for us by the tool itself. This is the reason why it doesn't expect us to set the content-type header explicitly in this case. Please see how I've set only Authorization header while uploading the image file on my PC (Refer screenshot):

enter image description here

Authorization header is an optional header. It is required only if you've setup some sort of authentication on the web server. So if anonymous access is allowed on your website then Headers tab in your case should be empty i.e. no key value pairs at all.

Note: Just for information, the correct content type for image files in a POST request is multipart/form-data even though we don't need to set it explicitly in the tool. Screenshot in the question shows that Content-Type header is being set as application/x-www-form-urlencoded which is not right.

RBT
  • 24,161
  • 21
  • 159
  • 240
0

In the post you referrer to the data is being uploaded as "x-www-form-url-encoded"

Your Postman screen shot shows you are uploading it as "form-data"

Additionally, you adding a key "image01" where the ARC example doesn't appear to be sending a key.

If you want to upload the file using form-data you need a different approach:

// POST api/files
public async Task<HttpResponseMessage> Post()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    string value;

    try
    {
        // Read the form data and return an async data.
        var result = await Request.Content.ReadAsMultipartAsync(provider);

        // This illustrates how to get the form data.
        foreach (var key in provider.FormData.AllKeys)
        {
            foreach (var val in provider.FormData.GetValues(key))
            {
                // return multiple value from FormData
                if (key == "value")
                    value = val;
            }
        }                       

        if (result.FileData.Any())
        {                    
            // This illustrates how to get the file names for uploaded files.
            foreach (var file in result.FileData)
            {
                FileInfo fileInfo = new FileInfo(file.LocalFileName);
                if (fileInfo.Exists)
                {
                   //do somthing with file
                }
            }
        }


        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value);
        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id }));
        return response;
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41
  • On the headers , I have mentioned content type as x-www-form-url-encoded and then selected formdata to upload image. If I select 'x-www-form-url-encoded ' on postman there is no option to upload image. – Simsons Jul 13 '17 at 00:44
  • Did an edit to show content type on screen shot as well – Simsons Jul 13 '17 at 00:47
  • See my update. If you want to use form data with a key you need a different approach. Also, your update makes it appear as if you uploaded the file using x-www when you didn't. – Alexander Higgins Jul 13 '17 at 00:52