如何使用ajax上传文件到asp.net mvc控制器动作 [英] How to upload files using ajax to asp.net mvc controller action

查看:21
本文介绍了如何使用ajax上传文件到asp.net mvc控制器动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个提交代码,

$('#form').on('submit',function (e) {
    e.preventDefault();
    //var file = $("#productImg");
    var fileUpload = $("#productImg").get(0);
    var files = fileUpload.files;


    var form = $("#form");
    var formData = new FormData();
    formData.append("product", form.serialize());

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

    $.ajax({
        type: 'POST',
        url: baseUrl + 'Controller/Action',
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {
        }
    });
});

这是我的控制器:

  public JsonResult AddProduct(ProductModel product) // data is binded in the model if I remove content type property
    {
        var isSuccess = false;

        if (product != null)
        {
            try
            {
                if (Request.Files.Count > 0) // works ok if I added the content type property
                {
                    var sadas = "sad";
                }

所以这里发生的是我将 serialized form 数据与上传的文件一起发送到 mvc 控制器中.

So what's happening here is I sending the serialized form data into mvc controller together with the uploaded file.

这里的问题是,当我添加这个ajax属性contentType:false,时,我可以成功回发文件,但绑定的模型为空.

The problem here is , when i added this ajax property contentType: false,, I can successfully postback the files, but the binded model is null.

另一方面,如果我删除此属性,则绑定模型可以正常工作.但问题是文件没有发送到服务器.

On the other hand, If i remove this property, the binded model works OK. But the problem is the file was not sent in the server.

我怎样才能做到这一点?我希望表单和图像都在服务器端发送.

How can I make this work? I want both the form and images to be sent in server side.

更新这是现在工作,我改变的唯一一行是这个

UPDATE This is working now, the only line I changed is this

formData.append("product", form.serialize());

var other_data = $('#addProductForm').serializeArray();$.each(other_data, function (key, input) {formData.append(input.name, input.value);});

有人能解释一下发生了什么吗?我什么都不知道

Can someone explain what is happening? I got no clue

推荐答案

不幸的是,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  
}

这篇关于如何使用ajax上传文件到asp.net mvc控制器动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆