gpt4 book ai didi

javascript - 无法将图像文件从 React 前端发布到 Express 和 MySQL

转载 作者:行者123 更新时间:2023-11-29 15:28:59 25 4
gpt4 key购买 nike

我在 React 中使用 axios 来发布用户通过 dropzone 区域上传的图像。我可以从前端看到console.log(this.state.faceImage)。但不知何故, express 收到了一个空对象,无法将其插入数据库。

服务器.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 (?)';

关于javascript - 无法将图像文件从 React 前端发布到 Express 和 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58885916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com