.net-4.0 – 上传文件MVC 4 Web API .NET 4

我正在使用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;
    }

但是这段代码总是以continueWith结尾,其中t.IsFaulted == true.例外情况如下:

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

这是我的客户表格.没什么好看的,我想做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中不起作用?

解决方法

您缺少文件输入的名称属性.
<form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" >
    <input name="myFile" type="file" />
    <input type="submit" value="Upload" />
</form>

没有它的输入将不会被浏览器提交.所以你的formdata是空的,导致IsFaulted被断言.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些