MERN Stack - 使用 Axios 将文件发送到服务器
MERN Stack - Sending file to server using Axios
我查看了很多关于堆栈溢出的帖子,但到目前为止我没有找到对我有帮助的东西。我正在尝试使用 MERN 堆栈将图像(文件)从我的客户端发送到我的服务器。我正在尝试使用 Multer 解析图像并使用 AXIOS 将数据发送到我的服务器端。
使用 Postman 效果很好,但是如果我尝试通过我的 React 前端发送数据,它就不起作用。
我想知道为什么从客户端发送的图片在服务器端收不到
客户端代码
this.onChangeName = this.onChangeName.bind(this);
this.onChangeRetreatImage = this.onChangeRetreatImage.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state= {
name : "",
retreatImage : null
}
onChangeName(event){
this.setState({
name : event.target.value
})
}
onChangeRetreatImage(event){
this.setState({
retreatImage : event.target.files[0]
})
}
onSubmit(event){
event.preventDefault();
console.log("Submit form : ", this.state)
const newRetreat = {
name : this.state.name,
retreatImage : this.state.retreatImage
}
axios.post('http://localhost:1234/retreats/addRetreat', newRetreat)
.then(res => console.log(res.data));
}
JSX
<form onSubmit={this.onSubmit} encType="multipart/form-data">
<div className="form-group">
<label>Retreat Name</label>
<input
type="text"
value={this.state.name}
onChange={this.onChangeName}>
</input>
</div>
<div className="form-group">
<label>Upload Images:</label>
<input
type="file"
name="retreatImg1"
onChange={this.onChangeRetreatImage}
</input>
</div>
<div className="form-group">
<input type="submit" value="Create retreat" className="btn btn-primary"></input>
</div>
</form>
)}
当我提交表单时,我看到 this.state.retreatImage 已填充:
image of screenshot of form submit
但是在我的服务器端我有 req.file undefined
和 req.body 作为 { name : foo, retreatImage : {} }
所以我猜测要么是我的 React 前端没有正确发送表单数据,要么是 multer 在使用 AXIOS 发送时没有正确解析它,如上所述,使用邮递员时一切都按预期工作。
路由选择
const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
cb(null, file.originalname + new Date().toISOString());
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
}
});
router.post('/addRetreat', upload.single('retreatImg1'), retreatController.addRetreat);```
(我在我的 retreatController 中记录 req.file 和 req.body)
撤退模式
const retreatSchema = new Schema({
name : { type : String },
retreatImage : { data : Buffer }
});
在此先感谢您提供的任何帮助。
我不熟悉向堆栈溢出问题发布问题,所以如果有任何我可以做的更清楚的事情,请告诉我。
我找到了答案,我需要将数据作为 FormData 发送并相应地更新 headers
onSubmit(event){
//prevent default form logic
event.preventDefault();
const formData = new FormData()
formData.append('name', this.state.name);
//sending multiple images so had to loop through
for(var j = 0; j < this.state.retreatImages.length; j++){
formData.append(
'retreatImages',
this.state.retreatImages[j],
this.state.retreatImages[j].name
)
}
console.log("Submit form : ", this.state)
// set headers to pass as final argument in axios post
const headers = {
Authorization : "Bearer " + token,
'Content-Type': 'multipart/form-data'
}
axios.post('http://localhost:1234/retreats/addRetreat', formData, {
headers : headers
})
.then(res => console.log(res.data));
我查看了很多关于堆栈溢出的帖子,但到目前为止我没有找到对我有帮助的东西。我正在尝试使用 MERN 堆栈将图像(文件)从我的客户端发送到我的服务器。我正在尝试使用 Multer 解析图像并使用 AXIOS 将数据发送到我的服务器端。
使用 Postman 效果很好,但是如果我尝试通过我的 React 前端发送数据,它就不起作用。
我想知道为什么从客户端发送的图片在服务器端收不到
客户端代码
this.onChangeName = this.onChangeName.bind(this);
this.onChangeRetreatImage = this.onChangeRetreatImage.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state= {
name : "",
retreatImage : null
}
onChangeName(event){
this.setState({
name : event.target.value
})
}
onChangeRetreatImage(event){
this.setState({
retreatImage : event.target.files[0]
})
}
onSubmit(event){
event.preventDefault();
console.log("Submit form : ", this.state)
const newRetreat = {
name : this.state.name,
retreatImage : this.state.retreatImage
}
axios.post('http://localhost:1234/retreats/addRetreat', newRetreat)
.then(res => console.log(res.data));
}
JSX
<form onSubmit={this.onSubmit} encType="multipart/form-data">
<div className="form-group">
<label>Retreat Name</label>
<input
type="text"
value={this.state.name}
onChange={this.onChangeName}>
</input>
</div>
<div className="form-group">
<label>Upload Images:</label>
<input
type="file"
name="retreatImg1"
onChange={this.onChangeRetreatImage}
</input>
</div>
<div className="form-group">
<input type="submit" value="Create retreat" className="btn btn-primary"></input>
</div>
</form>
)}
当我提交表单时,我看到 this.state.retreatImage 已填充: image of screenshot of form submit
但是在我的服务器端我有 req.file undefined
和 req.body 作为 { name : foo, retreatImage : {} }
所以我猜测要么是我的 React 前端没有正确发送表单数据,要么是 multer 在使用 AXIOS 发送时没有正确解析它,如上所述,使用邮递员时一切都按预期工作。
路由选择
const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
cb(null, file.originalname + new Date().toISOString());
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
}
});
router.post('/addRetreat', upload.single('retreatImg1'), retreatController.addRetreat);```
(我在我的 retreatController 中记录 req.file 和 req.body)
撤退模式
const retreatSchema = new Schema({
name : { type : String },
retreatImage : { data : Buffer }
});
在此先感谢您提供的任何帮助。
我不熟悉向堆栈溢出问题发布问题,所以如果有任何我可以做的更清楚的事情,请告诉我。
我找到了答案,我需要将数据作为 FormData 发送并相应地更新 headers
onSubmit(event){
//prevent default form logic
event.preventDefault();
const formData = new FormData()
formData.append('name', this.state.name);
//sending multiple images so had to loop through
for(var j = 0; j < this.state.retreatImages.length; j++){
formData.append(
'retreatImages',
this.state.retreatImages[j],
this.state.retreatImages[j].name
)
}
console.log("Submit form : ", this.state)
// set headers to pass as final argument in axios post
const headers = {
Authorization : "Bearer " + token,
'Content-Type': 'multipart/form-data'
}
axios.post('http://localhost:1234/retreats/addRetreat', formData, {
headers : headers
})
.then(res => console.log(res.data));