Upload a file MVC 4 Web API .NET 4

10,696

You are missing a name attribute on your file input.

<form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" >
    <input name="myFile" type="file" />
    <input type="submit" value="Upload" />
</form>

Inputs without it will not get submitted by the browser. So your formdata is empty resulting in IsFaulted being asserted.

Share:
10,696
JayPrime2012
Author by

JayPrime2012

Updated on July 10, 2022

Comments

  • JayPrime2012
    JayPrime2012 almost 2 years

    I'm using the version of MVC that shipped with Visual Studio 2012 express. (Microsoft.AspNet.Mvc.4.0.20710.0)

    I assume this is RTM version.

    I've found plenty of examples online which all use this code:

        public Task<HttpResponseMessage> PostFormData()
        {
            // 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);
    
            // Read the form data and return an async task.
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }
    
                    // This illustrates how to get the file names.
                    foreach (MultipartFileData file in provider.FileData)
                    {
                        Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                        Trace.WriteLine("Server file path: " + file.LocalFileName);
                    }
                    return Request.CreateResponse(HttpStatusCode.OK);
                });
    
            return task;
        }
    

    But this code always ends up in continueWith where t.IsFaulted == true. The exception reads:

    Unexpected end of MIME multipart stream. MIME multipart message is not complete.

    Here is my client form. NOthing fancy, I want to do jquery form pluging for ajax upload, but I can't even get this way to work.

    <form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" >
        <input type="file" />
        <input type="submit" value="Upload" />
    </form>
    

    I've read that it is caused by the parser expecting /CR /LF at the end of each message, and that bug has been fixed in June.

    What I cannot figure out is, if it was really fixed, why isn't it included this version of MVC 4? Why do so many examples on the internet tout that this code works when it does not in this version of MVC 4?