我是 react.js 和 ASP.Net core 2.0 的新手。现在编写一个使用 ASP.Net core 2.0 作为后端 API 和 react.js 作为应用程序接口(前端)的项目。我想知道如何上传文件。我已尝试如下,但在后端侧参数值(IFromFile 文件)始终为空。而且似乎该文件未正确发布。这是我的代码:
.Net 核心 (API)
[HttpPost]
[Route("upload")]
public async Task Upload(IFormFile file)
{
if (file == null) throw new Exception("File is null");
if (file.Length == 0) throw new Exception("File is empty");
using (Stream stream = file.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
var fileContent = binaryReader.ReadBytes((int)file.Length);
// await _uploadService.AddFile(fileContent, file.FileName, file.ContentType);
}
}
}
react.js
handleClick(event){
event.preventDefault();
// console.log("handleClick",event);
var self = this;
var apiBaseUrl = axios.defaults.baseURL + "user/upload";
if(this.state.filesToBeSent.length>0){
var filesArray = this.state.filesToBeSent;
const reader = new FileReader();
for(var i in filesArray){
//console.log("files",filesArray[i][0]);
var file = filesArray[i][0];
axios.post(apiBaseUrl, {data: file});
}
alert("File upload completed");
}
else{
alert("Please select files first");
}
}
请告诉我如何解决这个问题。