我正在使用ASP.NET Web API上传文件。我在RC之前这样做了,但由于某种原因,该文件被保存为“BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af”而不是文件名。下面的文件名变量也返回此bodypart字符串,而不是文件名。我似乎不知道我在哪里错了。任何帮助是赞赏。
客户代码:
function upload() { $("#divResult").html("Uploading..."); var formData = new FormData($('form')[0]); $.ajax({ url: 'api/files/uploadfile?folder=' + $('#ddlFolders').val(),type: 'POST',success: function (data) { $("#divResult").html(data); },data: formData,cache: false,contentType: false,processData: false }); };
控制器:
public Task<HttpResponseMessage> UploadFile([FromUri]string folder) { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType)); } // Save file MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/Files")); Task<IEnumerable<HttpContent>> task = Request.Content.ReadAsMultipartAsync(provider); return task.ContinueWith<HttpResponseMessage>(contents => { string filename = provider.BodyPartFileNames.First().Value; return new HttpResponseMessage() { Content = new StringContent(string.Format("File saved in {0}.",folder)) }; },TaskScheduler.FromCurrentSynchronizationContext());
文件看起来像: