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; }
}

8

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....
}

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;
}

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật