0

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");
    }
3
  • are you trying to cycle through multiple input areas? Commented May 23, 2018 at 12:39
  • data.append("file", program); I think each file must have an unique id. You are trying to name them all "file". Not sure, though Commented May 23, 2018 at 12:40
  • try this : data.append("file[]", program); Commented May 23, 2018 at 12:40

1 Answer 1

2

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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.