2

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

16
  • your function gets called and the returned code 400 means something wrong with the request data. You should update the question with your page handler MyUploader detail. Commented Dec 22, 2020 at 9:27
  • ok hopeless adding my other code Commented Dec 22, 2020 at 9:28
  • this kind of error can have its detail reported fairly well in the debugging console (the Output window). You should have a look in that window first. I doubt that the XSRF-TOKEN is not the right header for your antiforgery token. As in my recent project, I use RequestVerificationToken instead. Looks like it changes through different versions of asp.net core Commented Dec 22, 2020 at 9:34
  • @sabsudo Did you set services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); in ConfigureServices. Commented Dec 22, 2020 at 9:36
  • am using aspnet core 3.1 version, you want me to use RequestVerificationToken instead of XSRF-TOKEN Commented Dec 22, 2020 at 9:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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()

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.