shine
shine

Reputation: 100

How to append multiple files into formdata using jquery

I am using a input type file with multiple attribute. I want to save the files into a folder. But i am not sure how to append multiple files. Help will be greatly appreciated.

Script

$(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");
    }

Upvotes: 0

Views: 3654

Answers (1)

Keith
Keith

Reputation: 4147

If you are trying to cycle through the same input area, you can do:

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

Upvotes: 2

Related Questions