【问题标题】:trying to upload Image in mvc web api project using jquery ajax only尝试仅使用 jquery ajax 在 mvc web api 项目中上传图像
【发布时间】:2021-11-19 15:01:43
【问题描述】:

我正在尝试上传图像,但在运行我的应用程序时,我的图像参数传递为 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);
    }

在我的模型类中,我的 Image 数据类型为

public HttpPostedFileBase CurrentPicURL { get; set; }

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

【问题讨论】:

    标签: html asp.net asp.net-mvc asp.net-mvc-3 asp.net-web-api


    【解决方案1】:

    您不能使用JSON.stringify 通过 AJAX 上传文件。您需要使用FormData 类。

    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 而不是 AJAX。这可以简单得多,尤其是与async and await 结合使用时。

    【讨论】:

    • 先生,我明白你的意思,但在你的例子中,你在 ajax 的数据参数中传递数据,在哪里传递 ajax 中的 const 文件参数,先生,我希望你清楚我对此的理解跨度>
    • 文件被附加到FormData对象。
    • Sir @richarddeeming 我没有使用表单标签在我的 HTML 代码中,我已经在行和列模式中编写了带有表单标签的输入字段,我刚刚使用了 input-group 的引导 CSS 类我的所有输入字段和所有输入字段都在 div 标签中关闭,因为 FormData() 类在我的情况下不起作用,我想知道如果没有其他方法可以让我做到这一点需要在我的所有代码中添加表单标签
    • FormData 类不需要&lt;form&gt; 元素。 “不工作”究竟是什么意思?
    • 你是对的,我检查过并且不需要表单标签,但是当我运行代码并打开浏览器的检查工具并开始调试使用断点遍历我的代码的 ajax 部分时,我看到了我的 FormData { } 是空的,只有文件名已通过 ajax 传递,其余字段中的所有数据都没有通过 ajax 传递
    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多