asp.net-mvc ASP.NET Web API,从 Flex FileReference 上传时 MIME 多部分流意外结束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13770536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:28:02  来源:igfitidea点击:

ASP.NET Web API, unexpected end of MIME multi-part stream when uploading from Flex FileReference

asp.net-mvcapache-flexasp.net-web-api

提问by heyseuss

Following the tutorial found on ASP.NET, implemented a Web API controller method for doing asynchronous file uploads that looks like this:

按照 ASP.NET 上的教程,实现了一个 Web API 控制器方法来执行异步文件上传,如下所示:

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)
            {
                Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        });

    return task;
}

Uploading a file via a standard multipart HTML form works perfectly. However, when another developer attempts to upload a file via multipart form constructed by Flex's FileReference class, an error is thrown:

通过标准的多部分 HTML 表单上传文件非常有效。但是,当另一个开发人员尝试通过由 Flex 的 FileReference 类构造的多部分表单上传文件时,会引发错误:

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

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

I have no idea if the problem lies in Web API or Flex. I've found some sort of related fixes that had no affect (Multipart form POST using ASP.Net Web API), and more recently this one ("MIME multipart stream. MIME multipart message is not complete" error on webapi upload). If the second link holds true, does anyone know if it's out in the current release of Web API available via Nuget? The discussion was in May, the most recent release from Nuget was August, so I assume this fix was deployed already, and is not the root cause of my issue.

我不知道问题出在 Web API 还是 Flex。我发现了一些没有影响的相关修复(使用 ASP.Net Web API 的多部分表单 POST),以及最近的这个(“MIME 多部分流。MIME 多部分消息不完整”错误 webapi 上传)。如果第二个链接成立,有谁知道它是否在通过 Nuget 提供的当前版本的 Web API 中发布?讨论是在 5 月进行的,Nuget 的最新版本是 8 月,所以我认为此修复程序已经部署,并且不是我问题的根本原因。

采纳答案by Mark Jones

Reading through your existing research and following through to the codeplex issue reported it looks like someone else confirmed this issue to still exist in September.

通读您现有的研究并跟进 codeplex 问题报告说,其他人似乎在 9 月份确认此问题仍然存在。

They believe that MVC 4 fails to parse uploads without a terminating "\r\n".

他们认为 MVC 4 无法在没有终止“\r\n”的情况下解析上传。

The issue is really simple but extremely hard to fix. The problem is that Uploadify does > not add an "\r\n" at the end of the MultiPartForm message

这个问题真的很简单,但很难解决。问题是 Uploadify > 没有在 MultiPartForm 消息的末尾添加“\r\n”

http://aspnetwebstack.codeplex.com/discussions/354215

http://aspnetwebstack.codeplex.com/discussions/354215

It may be worth checking that the Flex upload adds the "\r\n"

可能值得检查 Flex 上传是否添加了“\r\n”

回答by Greg Sipes

I had the same problem with MVC4, but Will is correct, add a name to your input.....

我对 MVC4 有同样的问题,但 Will 是正确的,在您的输入中添加一个名称.....

<input type="file" id="fileInput" name="fileInput"/>

and all the magic is back up and working!

所有的魔法都恢复正常了!

回答by Landuber Kassa

I had the same problem with flex. And below is the code that solved it. Basically I used a custom stream to append the newline that asp.net web api is expecting.

我对 flex 有同样的问题。下面是解决它的代码。基本上我使用自定义流来附加 asp.net web api 期望的换行符。

        Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
        MemoryStream tempStream = new MemoryStream();
        reqStream.CopyTo(tempStream);



        tempStream.Seek(0, SeekOrigin.End);
        StreamWriter writer = new StreamWriter(tempStream);
        writer.WriteLine();
        writer.Flush();
        tempStream.Position = 0;


         StreamContent streamContent = new StreamContent(tempStream);
         foreach(var header in Request.Content.Headers)
         {
             streamContent.Headers.Add(header.Key, header.Value);
         }

        // Read the form data and return an async task.
         await streamContent.ReadAsMultipartAsync(provider);

Hope this helps.

希望这可以帮助。

回答by Niklas K?llander

For those landing here googling:

对于那些登陆这里谷歌搜索的人:

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

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

Reading the request stream more than once will also cause this exception. I struggled with it for hours until I found a source explaining that the request stream only could be read once.

多次读取请求流也会导致此异常。我为此苦苦挣扎了几个小时,直到找到一个解释请求流只能读取一次的来源。

In my case, I combined trying to read the request stream using a MultipartMemoryStreamProviderand at the same time letting ASP.NET do some magic for me by specifying parameters (coming from the request body) for my api method.

就我而言,我结合尝试使用 a 读取请求流MultipartMemoryStreamProvider,同时通过为我的 api 方法指定参数(来自请求正文)让 ASP.NET 为我做一些魔术。

回答by Sevda Ersezer

Make sure the virtual directory ("~/App_Data" directory as below example) where the image files are first uploaded are physically existance. When you publish the project, it may not be in the output files.

确保首次上传图像文件的虚拟目录(“~/App_Data”目录如下例)是物理存在的。发布项目时,它可能不在输出文件中。

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

回答by dk_french032

I just removed my headers I was setting on my post method which ended up solving this issue.

我刚刚删除了我在 post 方法上设置的标题,最终解决了这个问题。

回答by Luis Pardo

The problem is this line:

问题是这一行:

string root = HttpContext.Current.Server.MapPath("~/App_Data");

It will only work in localhost, you can use HostingEnvironment.MapPath instead in any context where System.Web objects like HttpContext.Current are not available (e.g also from a static method).

它只能在 localhost 中工作,您可以使用 HostingEnvironment.MapPath 而不是在 System.Web 对象(如 HttpContext.Current)不可用的任何上下文中(例如,也来自静态方法)。

var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SomePath");

See also What is the difference between Server.MapPath and HostingEnvironment.MapPath?

另请参阅Server.MapPath 和 HostingEnvironment.MapPath 之间有什么区别?

Reference to this answer How to do a Server Map Path.

参考这个答案How to do a Server Map Path。