我需要使用ajax在mvc4中上传多个文件 我尝试使用Ajax在mvc 4中使用以下代码上传文件:
frecuency = [2,2,2,1]
TrainIndex = [9,4,5,8]
[g for sublist in [[i]*f for (i,f) in zip(TrainIndex,frecuency)] for g in sublist]
[9, 9, 4, 4, 5, 5, 8]
我只是在脚本中提醒totalFiles,它返回选择上传的文件数。
我的控制器代码是:
$("input[type='file']").on("change", function () {
$("#upload").submit();
});
$("#upload").submit(function () {
var l = window.location;
var base_url = l.protocol + "//" + l.host;
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: base_url + '/ProductSpecific/Upload',
data: formData,
dataType: 'json', encode: true,
async: false,
processData: false,
cache: false,
success: function (data, status, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
由于文件上传的样式使用和css,因此查看页面代码为:
public ActionResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++) {
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/img"), fileName);
file.SaveAs(path);
}
return View();
}
但是控制器中的Request.Files.Count总是为0。
答案 0 :(得分:0)
请查看以下代码。我删除了内容类型字段并添加了enctype:'multipart / form-data'
$.ajax({
type: "POST",
url: base_url + '/ProductSpecific/Upload',
// data: { category: $('#ProductCategory').val(), description: $('#Description').val() },
data: formData,
enctype: 'multipart/form-data',
async: false,
processData: false,
cache: false,
//contentType: 'application/json; charset=utf-8',
success: function (data, status, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
答案 1 :(得分:0)
您还需要包含contentType: false,
ajax选项
$.ajax({
type: "POST",
url: '@Url.Action("Upload", "ProductSpecific")', // recommended
contentType: false, // add this
data: formData,
dataType: 'json',
encode: true,
async: false,
processData: false,
cache: false,
success: function (data, status, jqXHR) {
...
附注:您可以通过简单地使用
简化将文件添加到FormData
的代码
var formdata = new FormData($('#formbuttons').get(0));
将序列化所有表单控件,包括文件输入。您可以向方法添加参数以绑定文件
public ActionResult Upload(IEnumerable<HttpPostedFileBase> FileUpload)
{
....
}