如何使用jquery将多个文件附加到formdata

时间:2018-05-23 12:37:43

标签: c# jquery ajax file-upload

我正在使用具有多个属性的输入类型文件。我想将文件保存到文件夹中。但我不知道如何附加多个文件。非常感谢帮助。

脚本

$(document).on('click', '.btnSubmit', function () {
     var data = new FormData();
        var files = $('[type="file"]').get(0).files;

        if (files.length > 0) {
         _.each(files, function (program, idx) {
                data.append("file", program);
            });
        }
        _appFun._ajaxcall({
                type: "POST",
                url: '/application/test/saveFiles',
                type: 'POST',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                    //show content
                    alert('Success!')
                }
           });
});

C#

[HttpPost]
    public ActionResult saveFiles()
    {

        string directory = AppSettings.Application.uploadFolder;


        HttpPostedFileBase file = Request.Files["file"];

        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileNameWithoutExtension(file.FileName);

            string extension = Path.GetExtension(file.FileName);

            var randomId = uniqId();

            file.SaveAs(Path.Combine(directory, fileName + randomId + extension));
        }
        return RedirectToAction("Index");
    }

1 个答案:

答案 0 :(得分:2)

如果您尝试在同一输入区域中循环,则可以执行以下操作:

var data = new FormData();
var files = $('[type="file"]')[0].files;

if (files.length > 0) {
    var count = 0;
    $(files).each(function(i, value){
        count++;
        var variableName = "name" + count;
        data.append(variableName, value[i].files[0]);
    }
}