skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. As it is said in the comments. If you do not have a form tag in your page, for security reasons you need to protect from CSRF attacks, so you need to implement AddAntiforgery in your files.

    There are three key things you need to add:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");  //---> this line in Startup.cs class
        ...
    } 
    

    The following beforeSend method inside the ajax call:

    ...
    beforeSend: function (xhr) {
       xhr.setRequestHeader("XSRF-TOKEN",
           $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    ...
    

    And the following at the top of your razor page:

    @Html.AntiForgeryToken()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search