Home > Enterprise >  I am trying to save Image path database and the image itslef to a folder in project [closed]
I am trying to save Image path database and the image itslef to a folder in project [closed]

Time:09-28

I am working on web api and I am new to API's therefore it's really difficult for me to keep up with my project as I have created two projects one having the front-end and the other having the back-end, and the folder in which I want to save my Image after saving it's path to database is in my front-end project.

Here is my ajax which I have written in my front-end project this ajax hits my controller in which is in my back-end project:

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

});

please tell me in what form should I send Image from ajax and how becuase currently my Current PicUrl is only passing as string and in database it looks like this C:\fakepath\access-matrix-design.PNG, I want the whole Image to be passed through ajax and be saved in database along with it's path

here's my methods in my controller from my back-end project:

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

        EmployeeImage(emp, emp.CurrentPicURL);

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

    //Ajax call hit this method from AddEmployee page
    [Route("api/Employee/EmpOfficialDetails")]
    [HttpPost]
    public int? EmpOfficialDetails(Employee emp)
    {
        IHttpActionResult ret;
        try
        {
            var id = Emp_OfficialDetails(emp);
            return id;
        }
        catch (Exception ex)
        {
            ret = InternalServerError(ex);
        }
        return null;
    }

in above as you can see I am calling my EmployeeImage which I have created to save and process the Image but I do not know how to pass parameters to this method because of HttpPostedFileBase, and here is my method for processing the Image and saving the path of the image:

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

        byte[] bytes;
        using (BinaryReader br = new BinaryReader(CurrentPicURL.InputStream))
        {
            bytes = br.ReadBytes(CurrentPicURL.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) 


            CurrentPicURL.SaveAs(path);
        }
    }

please let me know how I may call this method in my EmpDetails mthod and pass my CurrentPicURL as parameter to this method, and this path "~/assets/img/profiles/employeeImages" I am referring to is located in my front-end project

All of the help I get is highly appreciated thank you

CodePudding user response:

$('.picture').val() will give you the filepath and name (C:\fakepath\access-matrix-design.PNG)

if you want to get file object, use $('.picture')[0].files[0]

  • Related