我有一个输入标签,如下所示:
<input type="file" name="file" accept="image/png, image/jpeg" class="choose">
<button id="bAddImage" type="button"> AddImage </button>
用户单击bAddImage
按钮后,如果用户选择了一个文件,该文件将保存在jQuery中的数组列表中,如下所示:
$('body').on('click',
'#bAddImage',
function(event) {
event.preventDefault();
if ($('.choose')[0].files[0] == null) {
return;
}
IMAGES.push({
File: $('.choose')[0].files[0],
});
});
我遇到的问题是这个列表中的文件。调用该方法后,这些文件将不会发送到服务器。
C#类
public class AddProductRequest
{
public string ProductNameEn { get; set; }
public List<HttpPostedFileBase> ProductImages { get; set; }
}
JavaScript中的调用方法
$('body').on('click',
'#bSubmit',
function(event) {
event.preventDefault();
var images = [];
if (IMAGES.length > 0) {
$.each(IMAGES,
function (index, item) {
images.push({
item.File
});
});
}
const formData = JSON.stringify({
ProductNameEn: 'test',
ProductImages: images *\not send value*
});
$.ajax({
type: "POST",
url: '@Url.Action("AdminApiAddProduct", "CallApi", new {area = "AdminArea"})',
contentType: "application/json",
dataType: "json",
data: formData,
success: function (response) {
},
error: function () {
}
});
});
控制台.log 中的formData
{"ProductNameEn":"测试","ProductImages":["{}"]}
发送ProductImages is null
,而images
具有值。
控制台.log 中的images
(1([…]0:文件{名称:"test.png",上次修改时间:1599110560934,大小:98288,…}长度:1:数组[]脚本:1:151
C#中的方法
[HttpPost]
public ActionResult AdminApiAddProduct(AddProductRequest request)
{
var nameEn = request.ProductNameEn; //test
if ((request.ProductImages ?? new List<HttpPostedFileBase>()).Count > 0)
{
**//Problem is NULL**
}
}
我遇到的全部问题是用户选择的文件没有发送到服务器,并且值为ProductImages = null
。
您必须使用FormData
而不是JSON,并将图像与其他数据一个接一个地附加到其中,我已经修改了您的代码
$(function () {
var formData = new FormData();
$('body').on('click',
'#bAddImage',
function (event) {
event.preventDefault();
if ($('.choose')[0].files[0] == null) {
return;
}
formData.append($(".choose")[0].files[0].name, $(".choose")[0].files[0]);
});
$("body").on("click", "#bSubmit", function (e) {
e.preventDefault();
$.ajax({
url: '/api/CallApi/AdminApiAddProduct',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (fileName) {
// success code
},
error: function (error) {
console.log(error);
}
});
});
在您的操作中使用HttpContext.Current.Request.Files
获取文件
[HttpPost]
[Route("api/CallApi/AdminApiAddProduct")]
public IHttpActionResult AdminApiAddProduct()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
return Ok("files uploaded!");
}
return Ok("no files to upload!");
}
catch (Exception ex)
{
throw ex;
}
}