javascript - 无法将图像文件从 React 前端发布到 express 和 MySQL
问题描述
我在 React 中使用 axios 来发布用户通过 dropzone 区域上传的图像。我可以从前端看到 console.log(this.state.faceImage)。但不知何故,快递收到了一个空对象,无法将其插入数据库。
server.js:
let INSERT_NEW_FACE_QUERY = 'INSERT INTO user_face SET ?';
app.post('/api/newface', (req, res) => {
console.log(req.body)
let data = req.body;
connection.query(INSERT_NEW_FACE_QUERY, data, (error, results) => {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
FaceForm.js:
<form noValidate className={classes.container} onSubmit={this.handleSubmit} autoComplete="off">
<DropzoneArea
dropzoneClass={classes.dropZone}
onChange={this.handleImageUpload.bind(this)}
dropzoneText='Upload Face Image (.jpg Format) Here'
acceptedFiles={['image/jpeg']}
filesLimit={1}
/>
<p>* The image should be clear and it should be forward-facing.</p>
<Button
type="submit"
variant="contained"
color="primary"
className={classes.button}
fullWidth>
SUBMIT
</Button>
</form>
下面是 handleSubmit 和 handleImageUpload 方法:
handleSubmit = (event) => {
alert('Form Submitted!');
event.preventDefault();
console.log(this.state.faceImage);
axios.post('http://localhost:4000/api/newface', this.state)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
handleImageUpload = (files) => {
this.setState({
faceImage: files
});
}
解决方案
我想到了。我必须使用 multer 和文件系统 fs。
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const fs = require('fs');
app.post('/api/newface', upload.single('faceImage'), (req, res) => {
const faceImage = req.file
fs.readFile(faceImage.path, (err, data) => {
connection.query(INSERT_NEW_FACE_QUERY, data, (error, results) => {
if (error) throw error;
res.end(JSON.stringify(results));
})
})
我将查询更改为:
INSERT_NEW_FACE_QUERY = 'INSERT INTO user_face (faceImage) VALUES (?)';
推荐阅读
- python - 在 scikit-learn 决策树中,您如何识别导致错误分类的决策?
- php - 扩展没有命名空间的类时出现致命错误
- html - 垂直居中按钮内的十字图标
- php - 未经身份验证的响应
- reactjs - 减少 TypeScript
- java - arrayImpOfStack.java 如何在输出中反转数字?
- android - 缺少 Google VR SDK 文件夹
- mysql - 使用派生值列查看
- javascript - 无法从 TokenProvider commercetools/sdk-auth 获取 access_token 和 token_type
- python - 如何将 Django 与 Azure Cosmos DB 连接