使用ajax上传图像文件,并在asp.net Core MVC控制器中接收图像文件 [英] Uploading image file with ajax and receiving it with in the asp.net core mvc controller
问题描述
我已经尝试过解决方案,但是没有任何进展.请帮忙.
I have tried all possible ways mentioned in this Solution, however didn't have any progress. Please help.
所以我的ajax请求如下:
So my ajax request is as below:
function photoUploadConfirmed() {
event.preventDefault();
var files = $("#image")[0].files;
var formData = new FormData();
formData.append("file", files[0]);
console.log(files); // I just check here and in browser I can see file name and size
console.log(formData); // I expect to see the same here, but here it almost shows empty
$.ajax({
type: "POST",
url: "/Account/ChangeProfilePicture",
data: { image: formData }, // In the controller it receives IFormFile image
processData: false,
contentType: false,
success: function () {
console.log("Done");
$("#profilePhoto").val('');
$("#profPicUploadConfirm").attr("disabled", true);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
}
控制器的动作接收到ajax发布请求,但是IFormFile图像始终为空.
The ajax post request gets received by the controller's action, however the IFormFile image is always null.
[HttpPost]
public async Task<IActionResult> ChangeProfilePicture(IFormFile image)
{
// I do save here the image in the folder, but problem is that image==null
}
推荐答案
Ajax发布请求被控制器的操作接收, 但是IFormFile图像始终为空.
The ajax post request gets received by the controller's action, however the IFormFile image is always null.
通过formData append上传文件时,此时的名称应与正在使用的接收参数的"image"
相同:
When the file is uploaded by formData append, the name at this time should be the same as "image"
of the receiving parameter in action:
formData.append("image", files[0]);
并且由于只需要将IFormFile传递给操作,因此在ajax
的 data 参数中,您只需要将formData附加到名为Image的文件上:
And because you only need to pass the IFormFile to the action, in the data parameter of ajax
, you only need to put the formData which appends the file named Image to it:
data: formData,
按如下所示更改您的js:
Change your js as follow:
function photoUploadConfirmed() {
event.preventDefault();
var files = $("#image")[0].files;
var formData = new FormData();
formData.append("image", files[0]);
console.log(files); // I just check here and in browser I can see file name and size
console.log(formData); // I expect to see the same here, but here it almost shows empty
$.ajax({
type: "POST",
url: "/Account/ChangeProfilePicture",
data: formData, // In the controller it receives IFormFile image
processData: false,
contentType: false,
success: function () {
console.log("Done");
$("#profilePhoto").val('');
$("#profPicUploadConfirm").attr("disabled", true);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
}
这是测试结果:
这篇关于使用ajax上传图像文件,并在asp.net Core MVC控制器中接收图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!