首页 > 解决方案 > 无法将图像文件从 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
        });
    }

标签: javascriptmysqlreactjsexpress

解决方案


我想到了。我必须使用 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 (?)';


推荐阅读