Upload file using multer after specific database operation in node js

房东的猫 提交于 2021-01-28 09:02:23

问题


I am using multer to upload files via express. Is there a way to perform a database operation before uploading the file? I need to perform a conditional check whether the user insertion in the database was successful or not depending on that, the file upload should be performed.


回答1:


To use multer as per required you can use the following code:

var path = require('path');
var multer = require('multer');

var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads')
    },
    filename: function(req, file, callback) {
        console.log(file)
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
});

destination is to specify the path to the directory where uploaded files will be stored.

filename is used to determine what the file should be named inside the folder. In this case, we upload the file using a return number value from Date.now() instead of the original name and add a original file extension using the built-in path Node.js library.

path.extname(file.originalname);

app.post('/insertUpload', function(req, res) {
    // connection  is db connection variable
    var username = req.body.username;
    var query = connection.query('INSERT INTO users SET ?', username,
      function(err, result) {
        console.log(result);
        if(!err){ // if not error after insert

          var upload = multer({
             storage: storage
          }).single('userFile')
          upload(req, res, function(err) {
            res.end('File is uploaded')
          });
        }
    });


});


来源:https://stackoverflow.com/questions/47466942/upload-file-using-multer-after-specific-database-operation-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!