我正在从angularJS向我的服务器发送一个文件对象 -
var fd = new FormData();
fd.append('file', file);
var deferred = $q.defer();
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(data, status, headers, config){
deferred.resolve(data);
})
.error(function(data, status, headers, config){
deferred.reject('some error occurred');
});
这是我的Asp.Net MVC控制器 -
public HttpResponseMessage Post([FromBody]HttpPostedFileBase file)
我想再发送一个带有相同请求的参数(比如userId)。有可能这样做吗?我应该如何在服务器端接收它。我尝试将fd.append('userId', userId)
添加到formdata对象,但它不起作用。请告诉我们如何实现这一目标。
提前致谢。
Edit1 :当我像我提到的那样绑定时,我得到以下错误:
Can't bind multiple parameters ('file' and 'userId') to the request'scontent.
Edit2 :我也尝试创建一个像这样的对象 -
public class PostedInfo{
public HttpPostedFileBase file {get;set;}
public string userId {get;set;}
}
并将post方法更改为 -
public HttpResponseMessage Post([FromBody]PostedInfo fd)
但是,现在抛出了这个错误,这很明显,因为请求是json -
The request entity's media type 'multipart/form-data' is not supported for this resource.
不知道如何判断fd.file是multipart/form-data
实体。
答案 0 :(得分:0)
我终于弄明白了。问题是HttpPostedFileBase似乎与webapi不能很好地协作,所以相反应该使用MultipartFormDataStreamProvider
。以下代码 -
[HttpPost]
public async Task<HttpResponseMessage> Post()
{
if (Request.Content.IsMimeMultipartContent())
{
string path = HttpContext.Current.Server.MapPath("~/Resources");
var provider = new MultipartFormDataStreamProvider(path);
await Request.Content.ReadAsMultipartAsync(provider);
// get the additional parameter
var userId = provider.FormData.GetValues("userId").FirstOrDefault();
string filepath = provider.FileData[0].LocalFileName;
return <your_custom_response_here>;
}
在这里,您可以看到,除了上传文件外,我还在服务器代码中获得了userId。
好吧,MultipartFormDataStreamProvider
将使用一个神秘的名称(BodyPart _...)保存文件。你可以通过构建自己的CustomMultipartFormDataStreamProvider来摆脱它。找到了一个很棒的link,关于如何在保存时格式化文件名。值得一读。