Need to fix my Ajax call to upload file and post to Controller

Coreysan 1,811 Reputation points
2022-05-18T00:53:31.427+00:00

I have some javascript that calls window.showOpenFilePicker, and gets the file opject.
That much works quite well with FormData.

However, when I call ajax to post to my controller, when I debug the action entry point Upload(IFormFile file), the variable "file" is still null.

I've seen some discussion in stackoverflow about this, but it didn't quite match my scenario.

Here's my javascript:

    <button id="formElem" onclick="getFile()">Open file</button>

    <script>
        const pickerOpts = {
            types: [
                {
                    description: "Images",
                    accept: {
                        "image/*": [".png", ".gif", ".jpeg", ".jpg"],
                    },
                },
            ],
            excludeAcceptAllOption: true,
            multiple: false,
        };

        async function getFile() {
            let [fileHandle] = await window.showOpenFilePicker(pickerOpts);
            const fileData = await fileHandle.getFile();

            console.log(fileData);

            var formData = new FormData();
            formData.append('image', fileData, fileData);

            $.ajax({
                type: "POST",
                url: "@(Url.Action("UploadFile", "Home"))",
                data: formData,
                processData: false,
                contentType: false,
                    success: function (response) {
                    }
            });
        }
    </script>
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-05-18T03:00:09.173+00:00

    Hi @Coreysan ,

      var formData = new FormData();    
    
         formData.append('image', fileData, fileData);  
    

    However, when I call ajax to post to my controller, when I debug the action entry point Upload(IFormFile file), the variable "file" is still null.

    The issue relates that the parameter name not matched.

    Try to change the formData as below:

         var formData = new FormData();  
         formData.append('file', fileData, fileData);  
    

    Or, change the controller's parameter name from file to image.

    The result as below:

    202977-2.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.