10

the model:

public class UploadFileModel
{
    public int Id { get; set; }
    public string FileName { get; set; }
    public HttpPostedFileBase File { get; set; }
}

the controller:

public void Post(UploadFileModel model)
{
     // never arrives...
}

I am getting an error

"No MediaTypeFormatter is available to read an object of type 'UploadFileModel' from content with media type 'multipart/form-data'."

Is there anyway around this?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
user10479
  • 790
  • 2
  • 9
  • 22
  • Possible duplicate of [WebAPI method that takes a file upload and additional arguments](https://stackoverflow.com/questions/23729458/webapi-method-that-takes-a-file-upload-and-additional-arguments) – Liam Jan 07 '19 at 16:52
  • You can use the MediaTypeFormatter to define a formatter to handle your media type data. A good explanation is here: http://blog.marcinbudny.com/2014/02/sending-binary-data-along-with-rest-api.html – sppc42 Oct 21 '15 at 14:22

1 Answers1

9

It's not easily possible. Model binding in Web API is fundamentally different than in MVC and you would have to write a MediaTypeFormatter that would read the stream of files into your model and additionally bind primitives which can be considerably challenging.

The easiest solution is to grab the file stream off the request using some type of MultipartStreamProvider and the other parameters using FormData name value collection off that provider

Example - http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2:

public async Task<HttpResponseMessage> PostFormData()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

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

    try
    {
        await Request.Content.ReadAsMultipartAsync(provider);

        // Show all the key-value pairs.
        foreach (var key in provider.FormData.AllKeys)
        {
            foreach (var val in provider.FormData.GetValues(key))
            {
                Trace.WriteLine(string.Format("{0}: {1}", key, val));
            }
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
Filip W
  • 27,097
  • 6
  • 95
  • 82