且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用ajax上传文件到asp.net mvc控制器动作

更新时间:2023-02-25 17:16:42

不幸的是,jQuery serialize() 方法将不包含输入文件元素.因此,您的文件不会包含在序列化值中.

Unfortunately the jQuery serialize() method will not include input file elements. So your files are not going to be included in the serialized value.

您可以做的是,创建一个 FormData 对象,将文件附加到该对象中.您还需要将表单字段值附加到同一个 FormData 对象.您可以简单地遍历所有输入字段并添加它.

What you can do is, creating a FormData object, append the files to that. You need to append the form field values as well to this same FormData object. You may simply loop through all the input field and add it.

当您将文件添加到表单数据时,您需要提供一个名称,该名称将与您将在 HttpPost 操作方法中使用的参数相匹配.

When you add the files to form data, you need to give a name which will match with the parameter you will use in your HttpPost action method.

这应该可行.

var fileUpload = $("#productImg").get(0);
var files = fileUpload.files;

var formData = new FormData();

// Looping over all files and add it to FormData object  
for (var i = 0; i < files.length; i++) {
    console.log('(files[i].name:' + files[i].name);
    formData.append('productImg', files[i]);
}

// You can update the jquery selector to use a css class if you want
$("input[type='text'").each(function (x, y) {
    formData.append($(y).attr("name"), $(y).val());
});

$.ajax({
    type: 'POST',
    url:  'ReplaceHereYourUrltotheActionMethod',
    data: formData,
    processData: false,
    contentType: false,
    success: function (data) {
    }
});

和您的操作方法,您可以添加另一个 IEnumerable 类型的参数,其名称与我们为表单数据设置的名称相同,即 productImg.

and your action method, You can add another parameter of type IEnumerable<HttpPostedFileBase> with the name same as what we set to form data, which is productImg.

[HttpPost]
public virtual ActionResult Index(ProductModel model, 
                                               IEnumerable<HttpPostedFileBase> productImg)
{
  // to do :Look through productImg and do something  
}