上传图像并将图像URL插入带有节点的mysql

问题描述 投票:-1回答:1

我有一个node.js应用程序,它上传图像并将它们存储在一个名为uploads的文件夹中。

我想将图像url存储在mysql数据库中,然后显示用html上传的所有图像。

我使用formidable上传图像。

app.get('/upload', function (req, res){
    res.sendFile(__dirname + '/index.html');
});

app.post('/up', function (req, res){
    var form = new formidable.IncomingForm();

    form.parse(req);

    form.on('fileBegin', function (name, file){
        file.path = __dirname + '/uploads/' + file.name;
    });



 form.on('file', function (name, file) {
        console.log('Uploaded ' + file.name);

        connection.query('SELECT * FROM images', (err, results) => {
            // Throw error if find function fails
            if (err) return (new Error(err));

            // Throw error if there is already a file with that name
            if (results[0]) return (new Error('File with that name already exists, please choose another name'));

            connection.query('INSERT INTO images', (error, results) => {


                // Throw error if save function fails
                if (err) return (new Error(err));

                // Throw error if you cannot verifty the save occured.

                if (results.affectedRows !== 1) return (new Error('There was an unexpected error. Please try again'));
                // Send Log to signal successfull upload
                console.log('Uploaded ' + file.name);
            });
        });
    });
});
mysql node.js express formidable
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.