如何使用 Axios 将多个文件发送到 ASP.NET Core 的控制器?
How to send multiple files to controller of ASP.NET Core using Axios?
我尝试了 IFormCollection 并尝试反序列化 JSON 但对我没有任何效果。我是 ASP.NET Core、React 和 Axios 的新手。我正在开发一项功能,用户可以上传多个文件并提供该事件的详细信息。
我使用了下面的代码。
uploadFiles() {
var eventDate = moment(this.state.dateOfEvent).format("DD/MM/YYYY");
var eDate = Date.parse(eventDate)
var formData = new FormData();
formData.append("Event_name", this.state.eventName);
var imgArr = [];
for (var i = 0; i < this.state.chosenImages.length; i++) {
imgArr.push(this.state.chosenImages[i]);
}
var jsonImgs = JSON.stringify(imgArr);
formData.append("Image_Path", jsonImgs);
formData.append("Event_Date", eventDate);
axios({
method: 'POST',
url: '/api/Account/UploadGalleryImages',
contentType: 'application/json',
data: formData,
}).then(function (response) {
if (response.data.status == "SUCCESS") {
confirmAlert({
title: 'Gallery',
message: response.data.message,
buttons: [
{
label: 'Okay',
onClick: () => window.location.replace('/Reload_Window')
},
]
});
}
else {
console.log("Response:", response);
confirmAlert({
title: 'Window Title',
message: response.data.message,
buttons: [
{
label: 'Okay',
},
]
});
}
}.bind(this))
}
反应代码
<FormGroup>
<Input
placeholder="Choose Image of Event"
type="file"
accept="image/jpeg,image/x-png"
multiple="multiple"
className="form-control"
onChange={(event) => this.handleChosenImages(event.target.files) }
/>
handleChosenImages(chosenFiles) {
this.setState({
chosenImages: chosenFiles
})
}
ASP.NET Core
中控制器的请求对象
public class GalleryImagesAddRequest
{
private string event_name;
private string event_date;
private IList<IFormFile> fileCollection;
public string Event_name { get => event_name; set => event_name = value; }
public IList<IFormFile> Image_Path { get => fileCollection; set => fileCollection = value; }
public string Event_Date { get => event_date; set => event_date = value; }
}
接收所有数据的控制器代码。
[HttpPost("UploadGalleryImages")]
[Route("api/[controller]/[action]")]
public string UploadGalleryImages(GalleryImagesAddRequest request)
{
Gallery gallery = new Gallery();
EventDetail eventDetail = new EventDetail();
Context db = new Context();
string message = "";
try
{
DateTime dateTime = DateTime.Parse(request.Event_Date).Date;
eventDetail.event_name = request.Event_name;
eventDetail.event_date = dateTime;
db.EventDetail.Add(eventDetail);
db.SaveChanges();
message = "SUCCESS";
}catch(Exception ex)
{
new Logger().write(ex);
message = "failed";
}
return message;
}
请有人告诉我在服务器端尝试接收所有图像时哪里出错了?
首先,您不需要序列化文件数组,其次,为了在 ASP.NET Core
中绑定一个数组,您需要将具有相同键的多个值附加到 FormData
.所以更改这部分代码
var imgArr = [];
for (var i = 0; i < this.state.chosenImages.length; i++) {
imgArr.push(this.state.chosenImages[i]);
}
var jsonImgs = JSON.stringify(imgArr);
formData.append("Image_Path", jsonImgs);
到
for (var i = 0; i < this.state.chosenImages.length; i++) {
formData.append("Image_Path", this.state.chosenImages[i]);
}
我尝试了 IFormCollection 并尝试反序列化 JSON 但对我没有任何效果。我是 ASP.NET Core、React 和 Axios 的新手。我正在开发一项功能,用户可以上传多个文件并提供该事件的详细信息。
我使用了下面的代码。
uploadFiles() {
var eventDate = moment(this.state.dateOfEvent).format("DD/MM/YYYY");
var eDate = Date.parse(eventDate)
var formData = new FormData();
formData.append("Event_name", this.state.eventName);
var imgArr = [];
for (var i = 0; i < this.state.chosenImages.length; i++) {
imgArr.push(this.state.chosenImages[i]);
}
var jsonImgs = JSON.stringify(imgArr);
formData.append("Image_Path", jsonImgs);
formData.append("Event_Date", eventDate);
axios({
method: 'POST',
url: '/api/Account/UploadGalleryImages',
contentType: 'application/json',
data: formData,
}).then(function (response) {
if (response.data.status == "SUCCESS") {
confirmAlert({
title: 'Gallery',
message: response.data.message,
buttons: [
{
label: 'Okay',
onClick: () => window.location.replace('/Reload_Window')
},
]
});
}
else {
console.log("Response:", response);
confirmAlert({
title: 'Window Title',
message: response.data.message,
buttons: [
{
label: 'Okay',
},
]
});
}
}.bind(this))
}
反应代码
<FormGroup>
<Input
placeholder="Choose Image of Event"
type="file"
accept="image/jpeg,image/x-png"
multiple="multiple"
className="form-control"
onChange={(event) => this.handleChosenImages(event.target.files) }
/>
handleChosenImages(chosenFiles) {
this.setState({
chosenImages: chosenFiles
})
}
ASP.NET Core
中控制器的请求对象 public class GalleryImagesAddRequest
{
private string event_name;
private string event_date;
private IList<IFormFile> fileCollection;
public string Event_name { get => event_name; set => event_name = value; }
public IList<IFormFile> Image_Path { get => fileCollection; set => fileCollection = value; }
public string Event_Date { get => event_date; set => event_date = value; }
}
接收所有数据的控制器代码。
[HttpPost("UploadGalleryImages")]
[Route("api/[controller]/[action]")]
public string UploadGalleryImages(GalleryImagesAddRequest request)
{
Gallery gallery = new Gallery();
EventDetail eventDetail = new EventDetail();
Context db = new Context();
string message = "";
try
{
DateTime dateTime = DateTime.Parse(request.Event_Date).Date;
eventDetail.event_name = request.Event_name;
eventDetail.event_date = dateTime;
db.EventDetail.Add(eventDetail);
db.SaveChanges();
message = "SUCCESS";
}catch(Exception ex)
{
new Logger().write(ex);
message = "failed";
}
return message;
}
请有人告诉我在服务器端尝试接收所有图像时哪里出错了?
首先,您不需要序列化文件数组,其次,为了在 ASP.NET Core
中绑定一个数组,您需要将具有相同键的多个值附加到 FormData
.所以更改这部分代码
var imgArr = [];
for (var i = 0; i < this.state.chosenImages.length; i++) {
imgArr.push(this.state.chosenImages[i]);
}
var jsonImgs = JSON.stringify(imgArr);
formData.append("Image_Path", jsonImgs);
到
for (var i = 0; i < this.state.chosenImages.length; i++) {
formData.append("Image_Path", this.state.chosenImages[i]);
}