我正在尝试使用 ajax、jquery 和 formdata 上传文件而不进行刷新。不幸的是,当我试图读取控制器中的文件时,它说文件是空的,我不知道为什么。
div“uploadForm”是表单本身。
查询:
$("#submitImage").click(function (event) {
event.preventDefault();
$('#uploadImage #submitImage').val('Uploading File..');
var formData = new FormData($('#uploadForm'));
$.ajax({
url: "Upload",
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
});
html:
@using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data", @id="uploadForm"}))
{
<input type="submit" value="Upload Image" id="submitImage"/>
<input type="file" name="file" id="bannerImage" value="Choose file" />
}
控制器:
[AcceptVerbs(HttpVerbs.Post)]
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
Functions Functions = new Functions();
string Filename = Functions.GenerateUniqueFileName();
if (file == null)
{
ViewBag.Test = "Ajax call complete, but the file is empty";
}
else
{
ViewBag.Test = "Ajax call complete, and the file isn't empty!";
}
return View();
}
}
现场演示: http: //upload.jamieknoef.nl/(您只需要使用选择文件和上传文件按钮)
编辑:已修复,请参阅我的其他帖子以获取答案!
提前致谢!