【发布时间】:2019-04-18 00:36:14
【问题描述】:
我尝试在 React 中使用 express 上传具有强大功能的图像,以将图像路径保存到数据库中。我阅读了这些教程:sequelize crud with expressjs 和Simple File Upload with Express.js and Formidable in Node.js 我遇到的问题是我无法混合从 React 上传图像并将 URL 保存到数据库中。
我的 React 代码中有这个用于设置状态:
picture(e){
this.setState({
picture:e.target.files[0]
});
console.log(e.target.files[0]);
}
在我的 render() 方法中,我只是处理它:
<input type="file" onChange={this.picture} className="form-control-file" placeholder="Picture" name="picture"/>
进入我的控制器我有这个代码:
exports.create = (req, res) => {
// Save to MySQL database
var form = new formidable.IncomingForm();
var fileName;
form.parse(req);
form.on('fileBegin', function (name, file){
fileName='/home/public_html/react-panel/img/' + file.name;
file.path = '/home/public_html/react-panel/img/' + file.name;
console.log('fileBegin ' + fileName);
});
form.on('file', function (name, file){
console.log('Uploaded ' + file.name);
});
StrongDish.create({
id: req.body.id,
name: req.body.name,
description: req.body.description,
picture: fileName,
category: req.body.category,
price: req.body.price
}).then(strongDish => {
// Send created customer to client
res.send(strongDish);
});
};
数据库中除ima文件外的其他数据一直保存
为了发帖,我只是用 redux 调用一个动作来发送状态数据
export const addStrongDish=dish=>async dispatch=>{
const response = await axios.post('http://www.my-domain.co.cr/api/dish/add/',dish);
dispatch({
type:ADD_DISH,
payload:response.data
})
}
【问题讨论】:
标签: node.js reactjs express redux sequelize.js