Home > Enterprise >  trying to upload Image in mvc web api project using jquery ajax only
trying to upload Image in mvc web api project using jquery ajax only

Time:09-28

I am trying to upload Image but upon running my application my Image parameter is passing null, and I don't know why it is not picking up the file I attached

but in my browser console when I check my image file object that if it is attached or not, it shows that it does attach

enter image description here

but in my controller its passing null

enter image description here

my ajax code where I am passing the image file object,

$('.empOfficialDetails').click(function (ev) {
    ev.preventDefault();

    var data = new Object();
    data.UserName = $('#username').val();
    data.UPassword = $('#userpass').val();
    data.OfficialEmailAddress = $('#officialemail').val();
    data.Departments = $('#departments :selected').text();
    data.Designation = $('#designation :selected').text();
    data.RoleID = $('#role').val();
    data.Role = $('#role :selected').text();
    data.ReportToID = $('#reportToID').val();
    data.ReportTo = $('#reportTo :selected').text();
    data.JoiningDate = $('#joindate').val();
    data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
    data.IsActive = $('#isActive :selected').val() ? 1 : 0;
    data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
    data.DateofPermanancy = $('#permanantdate').val();
    data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
    data.HiredbyReferenceName = $('#refePersonName').val();
    data.BasicSalary = $('#basicSalary').val();
    data.CurrentPicURL = $('.picture')[0].files; //this is my image file object
    //data.EmpID = $('.HiddenID').val();

    if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
        $.ajax({
            url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
            type: "POST",
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify(data),
            enctype: 'multipart/form-data',
            beforeSend: function () {
                $("#dvRoomsLoader").show();
            },
            complete: function () {
                $("#dvRoomsLoader").hide();
            },
            success: function (data) {
                var ID = parseInt(data);
                if (ID > 0) {
                    //var id = data;
                    $(".HiddenID").val(data);
                    //var id = $(".HiddenID").val();
                    $('#official').css('display', 'block');
                    $('#official').html("Employees Official details added successfully...!");
                    $('#official').fadeOut(25000);
                    $("#dvRoomsLoader").show();

                    $('.empOfficialDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
                }
                else {
                    $('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
                }
            },
            error: function (ex) {
                alert("There was an error while submitting employee data");
                alert('Error'   ex.responseXML);
                alert('Error'   ex.responseText);
                alert('Error'   ex.responseJSON);
                alert('Error'   ex.readyState);
                alert('Error'   ex.statusText);
            }
        });
        
    }
    return false;

});

but in controller on running the code it passes null

public void EmployeeImage(HttpPostedFileBase file)
    {
        var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
        var fileName = Path.GetFileName(file.FileName);
        var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)  

        byte[] bytes;
        using (BinaryReader br = new BinaryReader(file.InputStream))
        {
            bytes = br.ReadBytes(file.ContentLength);
        }

        if (allowedExtensions.Contains(ext)) //check what type of extension  
        {
            string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension  
            string myfile = name   "_"   ext; //appending the name with id  
            var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/assets/img/profiles/employeeImages"), myfile); // store the file inside ~/project folder(Img) 


            file.SaveAs(path);
        }
    }

    public int Emp_OfficialDetails(Employee emp)
    {
        //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
        var con = DB.getDatabaseConnection();
        SqlCommand com = new SqlCommand("sp_InsEmpOfficialDetails", con);
        com.CommandType = CommandType.StoredProcedure;

        #region Employee Official Details Insert Code block

        com.Parameters.AddWithValue("@UserName", emp.UserName);
        com.Parameters.AddWithValue("@pass", emp.UPassword);
        com.Parameters.AddWithValue("@OfficialEmailAddress", emp.OfficialEmailAddress);
        com.Parameters.AddWithValue("@Department", emp.Departments);
        com.Parameters.AddWithValue("@Role", emp.Role);
        com.Parameters.AddWithValue("@IsAdmin", Convert.ToBoolean(emp.IsAdmin));
        com.Parameters.AddWithValue("@Designation", emp.Designation);
        com.Parameters.AddWithValue("@ReportToID", emp.ReportToID);
        com.Parameters.AddWithValue("@ReportTo", emp.ReportTo);
        com.Parameters.AddWithValue("@JoiningDate", Convert.ToDateTime(emp.JoiningDate));
        com.Parameters.AddWithValue("@IsPermanent", Convert.ToBoolean(emp.IsPermanent));
        com.Parameters.AddWithValue("@DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
        com.Parameters.AddWithValue("@IsActive", Convert.ToBoolean(emp.IsActive));
        com.Parameters.AddWithValue("@HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
        com.Parameters.AddWithValue("@HiredbyReferenceName", emp.HiredbyReferenceName);
        com.Parameters.AddWithValue("@BasicSalary", emp.BasicSalary);
        com.Parameters.AddWithValue("@CurrentPicURL", emp.CurrentPicURL);

        #endregion
        var file = emp.CurrentPicURL;

        EmployeeImage(file);

        var ID = com.ExecuteScalar();
        com.Clone();
        return Convert.ToInt32(ID);
    }

and in my model class my Image datatype is as

public HttpPostedFileBase CurrentPicURL { get; set; }

I have no Idea what I am doing wrong If anyone who knows about this, your help is highly appreciated my friend

CodePudding user response:

You can't use JSON.stringify to upload a file via AJAX. You need to use the FormData class.

Sending files using a FormData object | MDN

const data = new FormData();
data.append("UserName", $('#username').val());
data.append("UPassword", $('#userpass').val());
...
const file = $('.picture')[0].files[0];
data.append("CurrentPicURL", file, file.name);
...

$.ajax({
    url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
    type: "POST",
    data: data,
    processData: false,
    contentType: false,
    beforeSend: function () {
        ...

NB: Unless you need to support Internet Explorer, you might want to use the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.

  • Related