mohammed alani1991
mohammed alani1991

Reputation: 93

Asp.net multiple files upload using Ajax

I am trying to upload multiple files but using ajax , i am facing two specific problems

first(java script problem): how to loop through input files and put it inside array of files before sending (by ajax)

second:(c# problem): how to receive the files in backend (what type of data should i use as parameter data type?)

here is my failed attempt:

html code:

<input type="file" name="file" accept=".pdf,.docx,.doc" class="drop-zone__input" multiple>

jQuery:

  <script>
    $(document).ready(function () {
        $('#addreply').click(

            function () {

                {
                    var files = $("#fileInput").get(0).files;
                    var fileData = new FormData();

                    for (var i = 0; i < files.length; i++) {
                        fileData.append("fileInput", files[i]);
                    }
                            var formData = new FormData();
                    //formData.append('file', $("[name='file']")[0].files[0]); // myFile is the input type="file" control
                    formData.append('reply', $("[name='reply']").val()); // myFile is the input type="file" control
                    formData.append('mid', @Model.Message.Id); // myFile is the input type="file" control
                    formData.append('files', fileData); // myFile is the input type="file" control

                    var _url = '@Url.Action("AddReplyDetails", "Messages")';
                        $.ajax({
                            url: _url,
                            type: 'POST',
                            data: formData,
                            processData: false,  // tell jQuery not to process the data
                            contentType: false,  // tell jQuery not to set contentType
                            success: function (result) {
                                //$('#file').val("")
                                $("#ssss").load(window.location + " #ssss").find('.rm').last().hide().fadeIn();
                                $('html, body').animate({
                                    scrollTop: $('.rm').last().offset().top
                                }, 2500);
                            },
                            error: function (jqXHR) {
                            },
                            complete: function (jqXHR, status) {
                            }

                        });

                }
                $("#reply").val('')

                });
    });
    </script>

backend:

   public async Task<IActionResult> AddReplyDetails(List<IFormFile> files,IFormFile file, string reply, int mid)
    {

        string filesnames="";
        foreach (var item in files)
        {
           filesnames +=await UserFile.UploadeNewFileAsync("", item, _environment.WebRootPath, Properties.Resources.Files);
            filesnames += ",";
        }
        Message message = _context.Messages.SingleOrDefault(m => m.Id == mid);
        message.LastActivitydate = DateTime.Now;
        message.IsRead = false;
        _context.Messages.Update(message);
        _context.MessageReplies.Add(new MessageReply
        {
            ApplicationUserId = _userManager.GetUserId(User),
            Content = reply.Replace("\n", "<br/>"),
            Attachment = filesnames,
            MessageId = mid,
            DateOfRecord = DateTime.Now,
            IsRead = false,
            IsDeleted = false,
            IsReported = false,
        });
        _context.SaveChanges();

        return RedirectToAction("Details", "Messages", new { id = mid });
    }

Upvotes: 0

Views: 4488

Answers (2)

user6583153
user6583153

Reputation:

Check on this link: https://www.c-sharpcorner.com/UploadFile/da55bf/multiple-files-upload-using-jquery-ajax-and-jqueryui-progres

upload multiple files at once and save them in a local folder with a progressbar

I did a few modifications on the above working example

  1. added additional parameters to formdata

    formData.append("LoanNo", $jq("#LoanNo").html()); formData.append("MemberNo", $jq("#MemberNo").html());

  2. and on the server side

    HttpFileCollection UploadedFilesCollection = context.Request.Files; string loanno = context.Request["LoanNo"].ToString(); string memberno = context.Request["MemberNo"].ToString();

Upvotes: 0

Anton Toshik
Anton Toshik

Reputation: 2909

Important thing to note is the parameter names

AddReplyDetails(List<IFormFile> files, IFormFile file, string reply, int mid)

so you have files, file, reply, mid

if you are posting FormData (which you will need if you are posting files)

You want to try to match the parameter names

var formData = new FormData();
formData.append('file', $("[name='file']")[0].files[0]);
formData.append('reply', $("[name='reply']").val());
formData.append('mid', @Model.Message.Id);
for (var i = 0; i < files.length; i++) {
    formData.append('files',files[i]);
}

and when posting include the content type header

headers: {'Content-Type': 'multipart/form-data'}

I would reccomend wrapping the above in a form object.

public class MyForm {
   public List<IFormFile> Files {get;set;} 
   public IFormFile File {get;set;}
   public string Reply {get;set;}
   public int Mid {get;set;}
}
// note the name of the parameter
AddReplyDetails([FromForm] MyForm form)

and then change FormData

var formData = new FormData();
formData.append('form.file', $("[name='file']")[0].files[0]);
formData.append('form.reply', $("[name='reply']").val());
formData.append('form.mid', @Model.Message.Id);
for (var i = 0; i < files.length; i++) {
    formData.append('form.files',files[i]);
}

Upvotes: 1

Related Questions