我正在使用 ASP.NET Web API 上传文件。我在 RC 之前已经这样做了,但由于某种原因,文件被保存为“BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af”而不是文件名。下面的文件名变量也返回此正文部分字符串,而不是文件名。我似乎无法弄清楚我要去哪里错了。任何帮助表示赞赏。
客户端代码:
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());
这些文件看起来像: