我正在嘗試上傳影像,但是在運行我的應用程式時,我的影像引數傳遞了 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 <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; }
我不知道我做錯了什么如果有人知道這一點,我的朋友非常感謝您的幫助
uj5u.com熱心網友回復:
您不能使用JSON.stringify通過 AJAX 上傳檔案。您需要使用FormData該類。
使用 FormData 物件發送檔案 | 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,否則您可能希望使用Fetch API而不是 AJAX。這可以簡單得多,尤其是與asyncandawait結合使用時。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415865.html
標籤:
