加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

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

发布时间:2020-12-14 21:13:33 所属栏目:资源 来源:网络整理
导读:我正在使用Visual Studio 2012 Express附带的MVC版本. (Microsoft.AspNet.Mvc.4.0.20710.0) 我假设这是RTM版本. 我在网上找到了很多使用这段代码的例子: public TaskHttpResponseMessage PostFormData() { // Check if the request contains multipart/form
我正在使用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被断言.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读