如何使用Express.js在React中上传图片

时间:2018-11-14 23:47:58

标签: node.js reactjs express redux sequelize.js

我试图在React和express中上传具有强大功能的图像,以将图像路径保存到数据库中。我阅读了以下教程:sequelize crud with expressjs  和Simple File Upload with Express.js and Formidable in Node.js 我遇到的麻烦是我无法混合从React上传图像并将URL保存到数据库中。

我在我的React Code中设置了状态:

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
    })
}

1 个答案:

答案 0 :(得分:0)

我解决了此问题,将其替换为multer