问题描述
我使用jQuery AJAX上传文件,但要添加上的WebAPI方法的一些参数,这里是:
I'm using jQuery ajax to upload file but want to add some parameters on webapi method, here is:
var data = new FormData();
data.append("file", $("#file")[0].files[0]);
data.append("myParameter", "test"); // with this param i get 404
$.ajax({
url: '/api/my/upload/',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log(data);
}
});
该控制器的WebAPI:
The Webapi controller:
public class MyController : ApiController
{
public string Upload(string myParameter)
{
return System.Web.HttpContext.Current.Request.Files.Count.ToString() + " / " + myParameter;
}
}
如果没有myParameter一切工作,但是当我包括FORMDATA和API方法,我得到404 myParameter,任何机会,以使其工作?
Without myParameter everything work but when I include myParameter on formdata and api method I get 404, any chance to make it work?
推荐答案
发布的 FORMDATA
对象的结果与内容类型的multipart / form-data的请求。你必须阅读像这样的要求的内容:
Posting the FormData
object results in a request with content type multipart/form-data. You have to read the request content like so:
[HttpPost]
public async Task<string> Upload()
{
var provider = new MultipartFormDataStreamProvider("C:\\Somefolder");
await Request.Content.ReadAsMultipartAsync(provider);
var myParameter = provider.FormData.GetValues("myParameter").FirstOrDefault();
var count = provider.FileData.Count;
return count + " / " + myParameter;
}
顺便说一句,这将保存在指定的路径的文件,这是 C:\\\\ SomeFolder
键,你可以使用获得本地文件名 provider.FileData [0] .LocalFileName;
BTW, this will save the file in the path specified, which is C:\\SomeFolder
and you can get the local file name using provider.FileData[0].LocalFileName;
请看看。
这篇关于阿贾克斯的WebAPI与FORMDATA额外的参数上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!