尝试仅使用 jquery ajax 在 mvc web api 项目中上传图像

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

我正在尝试上传图片,但在 运行 我的应用程序上,我的图片参数传递了 null,我不知道为什么它没有获取我附加的文件

但是在我的浏览器控制台中,当我检查我的图像文件对象时,如果它已附加或未附加,它会显示它确实已附加

但在我的控制器中它传递 null

我的 ajax 我传递图像文件对象的代码,

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

});

但在 运行 上的控制器中,它传递的代码为 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);
    }

在我的模型中 class 我的图像数据类型是

public HttpPostedFileBase CurrentPicURL { get; set; }

我不知道我做错了什么如果有人知道这件事,非常感谢你的帮助我的朋友

您不能使用 JSON.stringify 通过 AJAX 上传文件。您需要使用 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 () {
        ...

注意: 除非您需要支持 Internet Explorer,否则您可能需要使用 the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.