Dot-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 where 結束
t.IsFaulted == true。異常內容如下:MIME 多部分流的意外結束。MIME 多部分消息不完整。
這是我的客戶表格。沒什麼花哨的,我想為 ajax 上傳做 jquery 表單外掛,但我什至無法用這種方式工作。
<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 中不起作用?
您的文件缺少一個
name屬性input。<form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" > <input name="myFile" type="file" /> <input type="submit" value="Upload" /> </form>沒有它的輸入將不會被瀏覽器送出。所以你的表單數據是空的,導致
IsFaulted被斷言。