Multiple file upload in asp.net core using ajax on selection

Viewed 1651

Am new to asp.net core, I want to upload multiple files on user file selection with ajax in asp.net core. I use razor page with input file tag.

I follow each step of this article https://codepedia.info/ajax-file-upload-aspnet-core-razor-pages

I am able to call file selection event, but jquery ajax function not getting call, no debug on server side code hence no file upload. not single file upload. my code is not go in debug mode.

CODE

   $("#fileUpload").on('change', function () {

                var files = $('#fileUpload').prop("files");                
                var url = "/Index?handler=MyUploader";
                formData = new FormData();
                formData.append("MyUploader", files);              
               
                jQuery.ajax({
                    type: 'POST',
                    url: url,
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    success: function (repo) {
                        if (repo.status == "success") {
                            alert("File : " + repo.filename + " is uploaded successfully");
                        }
                    },
                    error: function (data) {

                        console.log(data);
                    }
                });
            });

ERROR SCREENSHOT

 public IActionResult OnPostMyUploader(IFormFile MyUploader)
        {
            if (MyUploader != null)
            {
                string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "mediaUpload");
                string filePath = Path.Combine(uploadsFolder, MyUploader.FileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    MyUploader.CopyTo(fileStream);
                }
                return new ObjectResult(new { status = "success" });
            }
            return new ObjectResult(new { status = "fail" });
    
        }
      

Formdata in browser console

1 Answers

The AntiForgeryToken is a hidden input auto-generated by a post form tag. At first, I have a form in the page, so I didn't add @Html.AntiForgeryToken() and it also worked. If there is no form in the page, then you should add @Html.AntiForgeryToken() to generate it.

Related