上传文件 MVC 4 Web API .NET 4

8

我正在使用随Visual Studio 2012 express一起提供的MVC版本。(Microsoft.AspNet.Mvc.4.0.20710.0)

我认为这是RTM版本。

我在网上找到了很多例子,它们都使用这段代码:

    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;
    }

但是这段代码总是在t.IsFaulted == true的continueWith中结束。异常信息如下:

意外地结束了MIME多部分流。 MIME多部分消息不完整。

这是我的客户端表单,没有什么花哨的东西,我想使用jquery表单插件进行ajax上传,但我甚至无法让这种方式工作。
<form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" >
    <input type="file" />
    <input type="submit" value="Upload" />
</form>

我读到它的原因是解析器期望在每条消息结尾处有/CR /LF,该错误已在6月修复。

我无法弄清楚的是,如果它真的被修复了,为什么它没有包含在这个版本的MVC 4中?为什么互联网上有那么多例子声称这段代码可以工作,但在这个版本的MVC 4中却行不通?


1
ASP.NET Web API不是ASP.NET MVC的一部分,它有自己的NuGet包。请检查您正在使用的版本。ASP.NET Web API 4.0.20710.0 - tpeczek
1个回答

19
您的文件输入标签缺少“name”属性。
<form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" >
    <input name="myFile" type="file" />
    <input type="submit" value="Upload" />
</form>

如果没有它,输入将无法被浏览器提交。因此,您的表单数据为空,导致 IsFaulted 被断言。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接