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

查看:269
本文介绍了如何使用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,时,我可以成功回传文件,但是绑定的模型为null.

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); });

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<HttpPostedFileBase>的参数,其名称与我们设置为表单数据的名称相同,即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天全站免登陆