创建注册表单,并将文件上传(图像)从 ajax 发送到服务器端 (C#)
本文关键字:图像 ajax 服务器端 表单 注册表 注册 文件 创建 | 更新日期: 2023-09-27 18:34:57
>我使用了ajax请求并在表单中包含上传文件(图像(。
这是我的代码:
.HTML:
@model acgs_qm.Models.StudentsData
@using (Html.BeginForm("RegisterStudent", "Admin", FormMethod.Post, new { id = "frmrs", enctype = "multipart/form-data" })){
<div id="ruCont">
<div class="first-inline">
<input type="file" id="si_image" name="si_image" accept="image/*" />
<div id="imgHolder"></div>
</div>
<div class="second-inline">
<span>Student ID:</span>
@Html.TextBoxFor(a => a.si_id, new { @class = "user-id-input"})
</div>
<div>
<span>Student Information</span>
<span class="field-name">Full Name:</span>
@Html.TextBoxFor(a => a.si_lname, new { @autocomplete = "off", @placeholder = "Last Name" })
@Html.TextBoxFor(a => a.si_fname, new { @autocomplete = "off", @placeholder = "First Name" })
@Html.TextBoxFor(a => a.si_mname, new { @autocomplete = "off", @placeholder = "Middle Name" })
</div>
<button class="ru-button" form="frmrs">Register Student</button>
</div>
}
.JS:
$(document).on("submit", "#frmrs", function (e) {
e.preventDefault();
frm = $(this);
formValidation();
formData = new FormData();
file = document.getElementById("si_image").files[0];
formData.append("si_image", file);
if ($(this).valid()) {
$.ajax({
url: '/admin/registerstudent',
type: 'POST',
data: frm.serialize() + '& si_image=' + formData,
processData: false,
contentType: false,
success: function () {
$.ajax({
url: '/admin/createstudent',
type: 'GET',
success: function () {
alert('Success!')
},
error: function () {
alert('Something went wrong.')
}
});
},
error: function () {
alert('Something went wrong!');
}
});
}
});
服务器端(C#(:
[HttpPost]
public ActionResult RegisterStudent(StudentsData sd, HttpPostedFileBase si_image)
{
_ActionModels ma = new _ActionModels();
if (si_image != null)
{
var versions = new Dictionary<string, string>();
var path = Server.MapPath("~/Content/profile-pic/");
versions.Add("_small", "maxwidth=500&maxheight=500&format=jpg");
foreach (var suffix in versions.Keys)
{
si_image.InputStream.Seek(0, SeekOrigin.Begin);
ImageBuilder.Current.Build(
new ImageJob(
si_image.InputStream,
path + si_image.FileName + suffix,
new Instructions(versions[suffix]),
false,
true));
}
}
ma.InsertStudentInfo(sd);
return RedirectToAction("CreateStudent");
}
问题是formdata
使用HttpPostedFileBase
向控制器返回一个 null,我不知道它为什么返回一个 null 值。
您的回复将不胜感激,提前感谢您。
Ajax 发送一个对象,你需要先做这样的事情
var Data = { Data: frm.serialize() + '& si_image=' + formData }
$.ajax({
url: '/admin/registerstudent',
type: 'POST',
data: Data,
processData: false,
contentType: false,
success: function () {
$.ajax({
url: '/admin/createstudent',
type: 'GET',
success: function () {
alert('Success!')
},
error: function () {
alert('Something went wrong.')
}
});
},
error: function () {
alert('Something went wrong!');
}
});