Javascript 使用multer和superagent从react上载文件
我是第一次使用multer,但遇到了一些麻烦 我想从带有superagent库的react客户端上传服务器上的图像文件 但是Javascript 使用multer和superagent从react上载文件,javascript,file,express,multer,superagent,Javascript,File,Express,Multer,Superagent,我是第一次使用multer,但遇到了一些麻烦 我想从带有superagent库的react客户端上传服务器上的图像文件 但是req.file数据始终未定义,下面是我的代码: 服务器端: const upload = multer({ dest: 'uploads/' }) app.post('/uploadprofile', upload.single('profil'), (req, res) => { console.log(req.file);
req.file
数据始终未定义,下面是我的代码:
服务器端:
const upload = multer({
dest: 'uploads/' })
app.post('/uploadprofile', upload.single('profil'), (req, res) => {
console.log(req.file);
console.log(req.files);
console.log(req.body);
res.status(200).end()
})
我的客户方面:
onUploadFile(e) {
console.log(e.target.files[0])
this.setState({
img: e.target.files[0]
}, () => {
agent
.post("http://localhost:3100/uploadprofile")
.attach('profil', this.state.img, this.state.img.name)
.set("Content-Type", "")
.end((err, res) => {
console.log(err)
console.log(res)
console.log("send")
})
})
}
render() {
return (
<input id="file" type="file" accept="image/*" name="profil" className="inputButton" onChange={this.onUploadFile}/>
)
}
onUploadFile(e){
console.log(e.target.files[0])
这是我的国家({
img:e.target.files[0]
}, () => {
代理人
.post(“http://localhost:3100/uploadprofile")
.attach('profile',this.state.img,this.state.img.name)
.set(“内容类型”,“”)
.end((错误、恢复)=>{
console.log(错误)
console.log(res)
控制台日志(“发送”)
})
})
}
render(){
返回(
)
}
在superagent请求中,我必须覆盖内容类型,否则将发送json数据
但是req.file
在我的后端仍然没有定义
谢谢你的帮助 问题在于您的superagent呼叫,请查看此页面: 据它说: 使用.field()或.attach()时,不能使用.send(),也不能设置内容类型(将为您设置正确的类型) 因此,您需要删除
.set(“内容类型”,“内容类型”)
,并执行以下操作:
await superagent
.post(url)
.withCredentials()
.accept('application/json')
.field('lets_try', 'ok!') // this would come from a form field
.attach('staff', event.target.files[0]); // this is your file
在服务器端,获得(单个)文件后,如果需要一些文本,仍然需要将其缓冲区转换为字符串:
console.log(`Uploaded req.body=${JSON.stringify(req.body)}`);
console.log(` req.file=${JSON.stringify(req.file, null, 2)}`);
console.log(`req.file=${req.file.buffer.toString()}`);
您将获得:
Uploaded req.body={"lets_try": "ok!"}
req.file={
"fieldname": "staff",
"originalname": "test.json",
"encoding": "7bit",
"mimetype": "application/json",
"buffer": {
"0": 10,
"1": 98,
"2": 111,
"3": 98,
"4": 10,
},
"size": 5,
}
req.file=
bob
如果你的文件内容是
bob
:-)你有没有弄明白这一点?我现在也有同样的问题。