【发布时间】:2017-11-03 02:48:59
【问题描述】:
我是新来的反应,我正在尝试将文件上传到我的节点后端,但我已经花了一段时间并且无法让它工作。我似乎正确地将数据发送到我的句柄函数,但之后我无法将其附加到我的 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]
虽然这是真的,但它无助于解决我的问题。
【问题讨论】:
-
我已经尝试过该解决方案,但它没有按我的需要工作。我将编辑我的评论。
标签: html forms file reactjs file-upload