0

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; }
}
8
  • Have you tried contentType: "multipart/form-data" ? Commented Sep 2, 2024 at 11:39
  • 1
    Your script checks if the user selected a file - but if they didn't, you still let it proceed with making the AJAX request. Commented Sep 2, 2024 at 11:42
  • tried this: contentType: "multipart/form-data" but still getting null value in controller Commented Sep 2, 2024 at 13:10
  • @C3roe is correct; if no file is selected, alert and just return. Commented Sep 2, 2024 at 21:45
  • hI @MANSICHANU, does your view contain form? 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. Your can prevent form's default submit behavior by using code like: $('#uploadImage').on('click', function (event) { event.preventDefault(); . Commented Sep 3, 2024 at 5:58

3 Answers 3

0

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....
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add the [FromForm] attribute to your form parameter.

Here is how i would implement it

public class ImageUploadModel
{
    public IFromFile ProfileImage {get; set;}
}

public async Task<ViewModel.BaseResponse> UploadImage([FromForm] ImageUploadModel model)
{
    ViewModel.BaseResponse Response = new ViewModel.BaseResponse();
    try
    {
        string email = HttpContext.Session.GetString("email"); 
        byte[] imageData;
        using (var memoryStream = new MemoryStream())
        {
            await model.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;
}

Comments

-1

So, it looks like you're not actually sending the formData to the server. You*re creating the object and adding the file, but then you're passing an empty object in the AJAX request. Try changing this to send the formData instead

$('#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);

        $.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!");
            }
        });
    }
});

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.