Uploading image to ASP.NET Core app using AJAX

Viewed 6996

I am new to jQuery and AJAX and I am trying to upload image to my server using it. I have a simple html page

<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<form method="post" enctype="multipart/form-data">
    Select image to upload:
    <input id="profilePic" name="picture" type="file" size="1" onchange="uploadFile('profilePic');" />
</form>

where script file is

function uploadFile(inputId) {
var fileUpload = $("#" +inputId).get(0);
var files = fileUpload.files;
var formData = new FormData();
formData.append(files[0].name, files[0]);

$.ajax({
    url: '/Image/File',
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function (result) {
    }
});

In my controller named ImageController I have a POST method named File which takes zero arguments:

[HttpPost]
public IActionResult File()
{
    var file = Request.Form.Files[0];

    if (file != null)
    {
        //work
    }

    return null;
}

but everytime I submit an image to form nothing happens and I get code 500: internal server error, failed to load resource. I have placed breakpoints in my code but it never entered the File method. What am I doing wrong? htmlpage and script are located in wwwroot, controller is in Controllers folder.

1 Answers

First, your action should take the image as a param:

// Don't use `File` here. You're hiding the base `File` method.
public IActionResult FileUpload(IFormFile file)
{
    // Always check content length
    if (file?.ContentLength > 0)
    {
        //work
    }

    return null;
}

Then, in your JS, the first param to FormData.append should be data name, not the name of the file. Since the action param is file, the name here should be file as well:

formData.append('file', files[0]);
Related