Upload a file MVC 4 Web API .NET 4

£可爱£侵袭症+ 提交于 2020-01-21 03:14:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/13074791/upload-a-file-mvc-4-web-api-net-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!