我正在使用 React 和 Axios 将 formData 发布到内部 .NET API。
API 需要这样的数据:
[HttpPost("upload")]
public virtual async Task<IActionResult> PostMulti(Int64 parentId, ICollection<IFormFile> fileData)
{
foreach (var file in fileData) {
await SaveFile(file, parent);
}
return Created("", Map(Repository.Get(parentId)));
}
当我单步执行调试器时,“fileData”的计数始终为 0。
这是我使用 Axios 发送它的方式:
const formData = new FormData();
formData.append('image', this.state.file);
console.log("this.state.file = ", this.state.file);
console.log("formData = ", formData);
axios({
url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
//handle success
console.log('response -- then: ', response);
this.setState({
file: this.state.file
});
})
.catch((response) => {
//handle error
console.log('response -- catch: ', response);
});
我使用 console.log 进行调试。当我写出来时,它会显示文件对象(名称、大小等)。
它还在方法的“.then”处理程序中触发并显示:
"response -- then: data: Array(0), status: 201, statusText: "Created" "
所以,我不知道为什么它没有向 API 发送任何内容,我也不知道发生了什么或如何解决这个问题。
如有任何帮助,我们将不胜感激。
谢谢!
最佳答案
您应该发布 formData
的数组
const filesToSubmit = []
filesToSubmit.push((new FormData()).append('image', this.state.file))
并且在发布数据时,属性名称应该是 formData
axios({
url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
method: 'POST',
data: {formData : filesToSubmit},
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
如果构建数组时出现问题,您需要将 IFormFile
属性添加到数组
关于javascript - 使用 Axios 将表单数据发布到 .NET API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50451025/