我正在尝试使用jQuery将文件发送到我的MVC控制器,但该操作始终接收到空的HttpPostedFileBase参数。
HTML:
<input type="file" name="file" id="file" />
<input type="submit" name="submit" id="upload" value="Submit"/>
jQuery的:
$(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
}
新的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) {
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句