我是 React 新手,我正在尝试将文件上传到我的节点后端,但我已经花了一段时间,但无法让它工作。我似乎将数据正确发送到我的句柄函数,但之后我无法将它附加到我的 formData 对象。
这是我在上传 html 的句柄提交按钮上调用的函数。
uploadAction(){
var self = this;
console.log('inside uploadAction');
var data = new FormData();
// var filedata = {};
var filedata = document.querySelector('input[type="file"]').files[0];
data.append('file', filedata);
console.log('this is the value of data in uploadAction ', data);
console.log('this is the value of filedata in uploadAction ', filedata)
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios.post('http://localhost:5000/upload',{
filedata: data
},config)
.then((response)=>{
console.log('back again success from upload');
})
.catch((err)=>{
console.error('error from upload ', err);
});
因此,当我在控制台注销数据和文件数据对象时,我得到以下结果。
this is the value of data in uploadAction FormData {}
this is the value of filedata in uploadAction File {name: "suck.jpg"....
所以不知何故,我的文件数据似乎被正确引入,但在如何将其附加到数据对象上存在脱节。这让我感到困惑,因为这似乎是我发现通过在线查看这些内容来附加此数据对象的方式。我认为我的 axios 调用是正确的,但在此之前我当然会遇到错误。
有没有人对我如何解决这个问题有任何建议?在不涉及使用 querySelector 的情况下,是否有更简单的方法来做到这一点?我可能不想使用 dropzone 或类似的库/包,我只是想学习如何做一个简单的上传文件。
如果有人对此有任何建议,我将不胜感激。我已经在这上面花了一些时间,但我似乎在兜圈子。
编辑:根据下面第一条评论的建议,我添加了
for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
我的代码尝试控制台记录我的数据值(即 dataForm 对象)。结果是:
file, [object File]
虽然这是事实,但它无助于解决我的问题。
最佳答案
将您的调用更改为以下方式,它应该可以工作(数据是您的 FormData):
axios.post('http://localhost:5000/upload',data,config)
除此之外,当您使用 React 时,您可以使用文件输入中的 onChange 事件,而不是使用 querySelector。 举个例子:
import React,{Component} from 'react'
class UploadComponent extends Component {
constructor(props, context) {
super(props, context);
this.state = {file: null};
this.handleFileChange = this.handleFileChange.bind(this);
this.sendFile = this.sendFile.bind(this);
}
handleFileChange(event) {
this.setState({file:event.target.files[0]})
}
sendFile() {
//In here you can get the file using this.state.file and send
}
render() {
return(
<div>
<input className="fileInput" type="file" onChange={this.handleFileChange}/>
<button type="submit" onClick={this.sendFile}>Upload </button>
</div>
)
}
}
关于html - 无法在 React 中上传文件时附加到 formData 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44316261/