我正在尝试使用 jQuery 将文件发送到我的 MVC 控制器,但该操作一直收到空 HttpPostedFileBase 参数。
HTML:
<input type="file" name="file" id="file" />
<input type="submit" name="submit" id="upload" value="Submit"/>
j查询:
$(function () {
$('#upload').click(function () {
var data = new FormData($('#file')[0].files[0]);
$.ajax({
url: '@Url.Action("Upload", "Home")',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false
});
});
});
控制器:
[HttpPost]
public virtual ActionResult Upload(HttpPostedFileBase file)
{
// file = null
}
new FormData($('#file')[0].files[0]):
__proto__: FormData
$('#file')[0].files[0]:
lastModified: 1445429215528
lastModifiedDate: Wed Oct 21 2015 14:06:55 GMT+0200 (Central Europe Daylight Time)
name: "Google_Chrome_logo_2011.jpg"
size: 5506
type: "image/jpg"
webkitRelativePath: ""
__proto__: File
我几乎复制了我在互联网上找到的其他示例的代码,但不知何故它就是不起作用。
试试这个:
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
var _file = Request.Files[file];
}
}
更新
var $file = document.getElementById('file'),
$formData = new FormData();
if ($file.files.length > 0) {
for (var i = 0; i < $file.files.length; i++) {
$formData.append('file-' + i, $file.files[i]);
}
}
$.ajax({
url: '/home/upload',
type: 'POST',
data: $formData,
dataType: 'json',
contentType: false,
processData: false,
success: function ($data) {
}
});
这是我的解决方案
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
如果您尝试将文件发送到控制器,您可以使用这种方法。
var formdata = new FormData();
formdata.append("YOUR_KEY", $("#ID_OF_Input_Type_File").prop('files')[0]);
$.ajax({
url: '/Home/UploadFile',
type: "POST",
data: formdata,
contentType: false, // Not to set any content header
processData: false, // Not to process data
success: function (result) {
alert(result);
},
error: function (err) {
alert(err);
}
});
你的控制器将如下所示。
public ActionResult UploadFile(HttpPostedFileBase YOUR_KEY)
{
// your file operations here....
return Json(result, JsonRequestBehavior.AllowGet);
}