locked
Drag and Drop file in Razor pages not uploading files to server RRS feed

  • Question

  • User-190697402 posted

    Hi,

    i have implemented the drag and drop file option for one of my forms, im able to drag and drop files which will list the files in the client side but its not uploading it to server,getting this error

    "Failed to load resource: the server responded with a status of 400 ()"

    Here is my frontend code.

    RequestForm.cshtml

    <tr>
                            <td>Attachments<span class="text-danger">*</span></td>
                            <td>
                                <div title="Please Drag and Drop Attachments" id="fileBasket" class="fileBasket">
                                    Drag And Drop Attachments
                                </div>
                                <br />
                                <img id="spinner" src="~/images/Spinner-3.gif" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                Uploaded Files:
                            </td>
                            <td>
                                <div id="uploadedFiles">
                                </div>
                                <input type="button" id="btnUpload" value="Upload" />
                            </td>
                        </tr>
    
    Javascript Code 
    
    $("#spinner").hide();
                $("#fileBasket").filedrop({
                    fallback_id: 'btnUpload',
                    fallback_dropzoneClick: true,
                    url: rootPath + "/Sales/RequestForm?handler=UploadFiles",
                    //allowedfiletypes: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/doc'],
                    allowedfileextensions: ['.doc', '.docx', '.pdf', '.jpg', '.jpeg', '.png', '.gif'],
                    paramname: 'fileData',
                    maxfiles: 3, //Maximum Number of Files allowed at a time.
                    maxfilesize: 2, //Maximum File Size in MB.
                    dragOver: function () {
                        $('#dropSection').addClass('active');
                    },
                    dragLeave: function () {
                        $('#dropSection').removeClass('active');
                    },
                    drop: function () {
                        $('#dropSection').removeClass('active');
                    },
                    error: function (err, file) {
                        switch (err) {
                            case 'BrowserNotSupported':
                                alert('Your browser does not support HTML5 file uploads!');
                                break;
                            case 'TooManyFiles':
                                alert('Too many files! Please select 3 at most!');
                                break;
                            case 'FileTooLarge':
                                alert(file.name + ' is too large! Please upload files up to 4mb.');
                                break;
                            case 'FileTypeNotAllowed':
                                alert(file.name + ' is not supported. You can only upload files with .gif .png and .jpg extension');
                                break;
                            default:
                                break;
                        }
                    },
                    uploadStarted: function (i, file, len) {
                        $("#spinner").show();
                    },
                    uploadFinished: function (i, file, response, time) {
                        $("#spinner").hide();
                        $('#uploadedFiles').append(file.name + '<br />');
                    },
                    afterAll: function (e) {
                        //To do some task after all uploads done.
                        //$("#RequestTypeNextBtn").removeAttr('disabled');
                    }
                });

    RequestForm.cshtml.cs code

    public ActionResult UploadFiles(List<IFormFile> fileData)
            {            
                foreach (IFormFile postedFile in fileData)
                {
                    string ext = Path.GetExtension(postedFile.FileName);
                    
                    //upload.FileName = EmpID + upload.FileName;
                    var filesave = Path.Combine(_env.WebRootPath, "Uploads", postedFile.FileName);
                    using (var stream = System.IO.File.Create(filesave))
                    {
                        postedFile.CopyToAsync(stream);
    
                    }
                }
    
                return Content("Success");
            }

    And is there any way to execute this upload functionality on form submission? Currently i have a submit functionality which will be executed after completing all the form fields.

    Wednesday, May 12, 2021 3:44 AM

All replies

  • User-821857111 posted

    "Failed to load resource: the server responded with a status of 400 ()"
    The reason for the 400 status code is because you haven't included a request verification token in your form submission. 

    https://www.mikesdotnetting.com/article/336/ajax-posts-in-razor-pages-and-http-400-errors

    The easiest way to deal with this is to opt out of request verification for that handler:

    [IgnoreAntiforgeryToken]
    public ActionResult UploadFiles(List<IFormFile> fileData)

    The safest way to deal with the issue is to include the token. The article tells you how.

    Wednesday, May 12, 2021 5:52 AM
  • User1686398519 posted

    Hi teenajohn1989, 

    The article in the link provided by @Mike perfectly explains why you got the 400 error.

    According to the code you provided, you seem to be using jQuery filedrop. You can modify your code like this:

    @page
    @model DailyRazorPageDemo.Pages.Index4Model
    @using Microsoft.AspNetCore.Antiforgery;
    @inject IAntiforgery antiforgery
    @{
        var token = antiforgery.GetAndStoreTokens(HttpContext).RequestToken;
    }
    <div title="Please Drag and Drop Attachments" id="fileBasket" class="fileBasket">
        Drag And Drop Attachments
    </div>
       Uploaded Files:
    <div id="uploadedFiles">
    </div>
    <input type="button" id="btnUpload" value="Upload" />
    @section scripts{
        <script src="~/jquery.filedrop.js"></script>
        <script>
            $("#fileBasket").filedrop({
                fallback_id: 'btnUpload',
                fallback_dropzoneClick: true,
                url: "/Index4?handler=UploadFiles",
                headers: { 			// Send additional request headers
                    "RequestVerificationToken": '@token'
                },
                //allowedfiletypes: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/doc'],
                maxfiles: 3, //Maximum Number of Files allowed at a time.
                maxfilesize: 2, //Maximum File Size in MB.
                dragOver: function () {
                    $('#dropSection').addClass('active');
                },
                dragLeave: function () {
                    $('#dropSection').removeClass('active');
                },
                drop: function () {
                    $('#dropSection').removeClass('active');
                },
                error: function (err, file) {
                    switch (err) {
                        case 'BrowserNotSupported':
                            break;
                        case 'TooManyFiles':
                            alert('Too many files! Please select 3 at most!');
                            break;
                        case 'FileTooLarge':
                            alert(file.name + ' is too large! Please upload files up to 4mb.');
                            break;
                        case 'FileTypeNotAllowed':
                            alert(file.name + ' is not supported. You can only upload files with .gif .png and .jpg extension');
                            break;
                        default:
                            break;
                    }
                },
                uploadStarted: function (i, file, len) {
                    $("#spinner").show();
                },
                uploadFinished: function (i, file, response, time) {
                    $("#spinner").hide();
                    $('#uploadedFiles').append(file.name + '<br />');
                },
                afterAll: function (e) {
                    //To do some task after all uploads done.
                    //$("#RequestTypeNextBtn").removeAttr('disabled');
                }
            });
        </script>
    }
    

    Here is the result. 

    Best Regards,

    YihuiSun

    Thursday, May 13, 2021 8:06 AM