尝试将文件和一些数据发布到MVC 5后端。
问题是它没有正确映射,因此它返回404.Http post请求作为multipart / form-data内容类型发送。
以下是角度服务的Http帖子
requestInputHeat: function (qty, date, camp, note, file1) {
return $http({
method: 'POST',
url: '/log/heat/request',
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
Quantity : qty,
RequestDate: date,
CampaignDetail: camp,
Notes: note,
File: file1
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
})
}
这是我试图接收此请求的控制器MVC5后端(使用mvcmapping atrributes)
[HttpPost]
[Route("log/heat/request")]
public ActionResult RequestPOHeat(string Quantity, string RequestDate, string CampaignDetail, string Notes, HttpPostedFileBase File)
{
......
}
答案 0 :(得分:0)
请尝试以下
在angularJs中
function requestInputHeat(qty, date, camp, note, file1) {
var request = {
method: 'POST',
//public ActionResult RequestPOHeat(string Quantity, string RequestDate, string CampaignDetail, string Notes)
//your Controller Action RequestPOHeat requires 4 query strings which was previously not send in your code which I had passed below. This was giving 404 error.
url: '/log/heat/request?Quantity=' + qty.toString() + '&RequestDate=' + date.toString() + '&CampaignDetail=' + camp.toString() + '&Notes' + note.toString(),// I don't know the datatype so had converted them to string.Please change them to corresponding type once it's working. Also don't forget to map type with RequestPOHeat method parameter of controller.
data: { file: file1 },
headers: {
//IMPORTANT!!! You might think this should be set to 'multipart/form-data'
// but this is not true because when we are sending up files the request
// needs to include a 'boundary' parameter which identifies the boundary
// name between parts in this multi-part request and setting the Content-type
// manually will not set this boundary parameter. For whatever reason,
// setting the Content-type to 'false' will force the request to automatically
// populate the headers properly including the boundary parameter.
'Content-Type': undefined
},
transformRequest: function (data) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
return formData;
},
};
return $http(request).success(function (result) {
return result.data;
}).error(function () {
});
}
在MVC控制器中
[HttpPost]
[Route("log/heat/request")]
public ActionResult RequestPOHeat(string Quantity, string RequestDate, string CampaignDetail, string Notes)
{
var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files(0) : null;
if (file != null && file.ContentLength > 0) {
//If file is posted you will get here..
}
......
}
提示:什么是赏金参数? 边界参数设置为多个连字符加上最后的随机字符串,但您可以将其设置为任何内容。问题是,如果边界字符串显示在请求数据中,它将被视为边界。