Search code examples
javascriptc#ajaxasp.net-coreform-data

sending image file using ajax to controller action getting null value in action parameter asp.net core


Hi there to all of you.

When I attempt to upload an image file using an Ajax call and send it to the controller action (asp.net core), sometimes I get an image file and sometimes get a null value in the controller action what could be the reason?

HTML:

<div class="form-group">
       <label>Profile Picture</label>
       <div class="row">
            <div class="col-md-9">
                    <input id="profilePicture" class="form-control form-control-lg" type="file" accept=".jpeg, .jpg, .png">
             </div>
             <div class="col-md-3">
                    <button id="uploadImage" type="submit" class="form-control form-control-lg btn btn-primary" style="color: white">Upload</button>
            </div>
        </div>
 </div>

JavaScript:

$('#uploadImage').on('click', function () {
    var fileInput = $('#profilePicture')[0];
    var file = fileInput.files[0];
    console.log(file);

    if (file === undefined || file === null) {
        alert("Please Select File");       
        console.log(file);
    }else{
        var formData = new FormData();
        formData.append('profileImage', file);
    }
    console.log(formData.get("profileImage"))

    $.ajax({
        url: '@Url.Action("UploadImage", "User")',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function (response) {
            if (response.flag) {
                toastr.success(response.message, "Success!");
            } else {
                toastr.error(response.message, "Error!");
            }
        },
        error: function (xhr, status, error) {
            alert("Some Issue Occurred Please Try Again");
            toastr.error("An error occurred while uploading the image.", "Error!");
        }
    });
});


Server Side Code:

public async Task<ViewModel.BaseResponse> UploadImage(IFormFile profileImage)
{
    ViewModel.BaseResponse Response = new ViewModel.BaseResponse();
    try
    {
        string email = HttpContext.Session.GetString("email"); 
        byte[] imageData;
        using (var memoryStream = new MemoryStream())
        {
            await profileImage.CopyToAsync(memoryStream);
            imageData = memoryStream.ToArray();
        }
        var imagebase64 = Convert.ToBase64String(imageData);
        
        var request = new UploadImageRequest
        {
            Email = email,
            ProfileImage = imagebase64
        };

        var authToken = string.Empty;
        var route = "UploadImage";
        var response = await DataHelper<ViewModel.BaseResponse>.Execute(route, OperationTypes.POST, authToken, request);
        if (response != null && response.Data != null)
        {
            Response.Flag = response.Flag;
            Response.Message = response.Message; 
        }
    }
    catch
    {
    }
    return Response;
}

UploadImageRequest Class:

public class UploadImageRequest
{
    public string Email { get; set; }
    public string ProfileImage { get; set; }
}

Solution

  • The button you are using to trigger the file upload is of type submit, which can cause a form submission event, potentially interfering with the AJAX call.

    You can prevent form's default submit behavior by using code like:

    $('#uploadImage').on('click', function (event) 
    {     
        event.preventDefault(); 
        //do your stuff....
    }