我正在尝试将图像和几个表单元素上传到MVC控制器。这里的问题不是未填充的模型,因为它与application/x-www-form-urlencoded
一起使用,但似乎与multipart/form-data
有问题。问题的核心是Request.Form
没有被填充......
将表单转换为FormData:
function frmValuesAsFormData(submittedForm) {
return new FormData(submittedForm);
}
AJAX函数(在这种情况下,asFormData作为True传入,方法是POST,dataType是JSON):
function executeAJAX(method, url, data, asFormData, silent, callbackFunc, receiveFunc, dataType, targetDiv, appendToExistingContent, uid) {
var cType = "application/x-www-form-urlencoded";
var processData = true;
if (asFormData) {
cType = "multipart/form-data";
processData = false;
}
$.ajax({
method: method,
url: url,
data: data,
contentType: cType,
cache: false,
dataType: dataType,
processData: processData,
success: function (d, t, j) {
// Do something with result from controller...
}
});
}
POST标题(来自FireBug)
接受application / json,text / javascript, / ; Q = 0.01 Accept-Encoding gzip,deflate Accept-Language en-GB,en; q = 0.5 Content-Length 936 Content-Type multipart / form-data Cookie ASP.NET_SessionId = mzppxvimv03qb0smtyrgdw3z主机localhost:64727 Referer http://localhost:64727/Home/Contact User-Agent Mozilla / 5.0 (Windows NT 10.0; Win64; x64; rv:50.0)Gecko / 20100101 Firefox / 50.0 X-Requested-With XMLHttpRequest
POST示例(来自FireBug):
----------------------------- 26439188689323 Content-Disposition:form-data; NAME = “的图像文件中”; filename =“WWKDK33.jpg”内容类型: 图像/ JPEG
PNG IHDR “ ” xÕj 7IDATxÚíÚK ÐÞÿÒzB3〜TH,OB!|!nHàøÈB “d” d B $ B “d” d B $ !B“Dcdtå]μ B “d!BÔKtb_xv-!B” Dunð+ UO “d!BNS * I” B“d!B(OL B“d!乙 ô¢IU·好不〜 “d乙¢URI,OO!” d BQ / Q:O![!* E “!dB¨a¼ÙôWÿéf” d乙¢] HAEL〜ED!B “DöÍ_ÉòGGkA” d!床±}Çõò4 !B “DZôÀ½rª” d!乙¢eD¡¡y¡éøk!乙 “!d ZGO;¯49ÛDB” d “COE @ FAQ ^ d乙!” D®I4_à|次@ĴB“DY(S°! “D!B¢{7£ÁÁ”D!B“D½DgBæant¿”D!BÑÖý¤ôm “d乙!” d “d乙$ B!” A “d d乙!” A“d SS |!ÜYÆ ®«IEND®B` ----------------------------- 26439188689323 Content-Disposition:form-data; NAME = “uploaderMode”
赛 ----------------------------- 26439188689323 -
任何有关它为何不起作用的线索?谢谢!
答案 0 :(得分:1)
问题是因为当您在请求中发送FormData
对象时,您必须将contentType
设置为false
,以便不会发送content-type
标头。试试这个:
if (asFormData) {
cType = false;
processData = false;
}
另请注意,只需检查asFormData
属性的类型,即可完全删除将data
属性发送到函数的需要:
if (data.constructor == FormData) {
cType = false;
processData = false;
}