【发布时间】:2014-05-30 10:32:05
【问题描述】:
我正在使用 Asp net web form 4.5.1 和 Asp net web Api,我试图将一些数据和文件发送到 Web Api 方法,
我的代码基于[http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2][1] 示例
但我想通过 AJAX (jquery) 发送数据
var formData = new FormData();
var opmlFile = $('#packFile')[0];
formData.append("opmlFile", opmlFile.files[0]);
formData.append("packageData", JSON.stringify(ko.mapping.toJS(this.selectedItem)));
$.ajax({
type: "POST",
url: "/api/MyController/MyMethod",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
},
failure: function (response) {
}
});
这似乎是可行的情况,但如果我在请求中发送文件,我的对象数据不可用(provider.FormData.AllKeys)。如何使它起作用?当然我可以发送 2 个请求,但这似乎对我不利。
public async Task<HttpResponseMessage> MyMethod()
{
// 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);
}
// 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);
}
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Trace.WriteLine(string.Format("{0}: {1}", key, val));
}
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return await task;
}
【问题讨论】:
标签: jquery asp.net ajax asp.net-web-api multipartform-data