Node.js保存上传的文件

时间:2019-03-12 11:59:01

标签: node.js mongoose multer

我有一个应用程序,并且在该应用程序中,我想使用某种文件上传机制。

我的要求是:

文件上传后,其名称将更改为唯一的名称,例如uuid4()。稍后,我将这个名称存储在数据库中。

我写了类似的东西,但是我有几个问题:

const multer = require('multer');
const upload = multer();
router.post('/', middleware.checkToken, upload.single('file'), (req,res,next)=>{

    // key:
    // file : "Insert File Here"

    console.log("req:");
    console.log(req.file);
    const str = req.file.originalname
    var filename = str.substring(0,str.lastIndexOf('.'));
    // I will use filename and uuid for storing it in the database
    // I will generate unique uuid for the document and store the document
    // with that name
    var extension = str.substring(str.lastIndexOf('.') + 1, str.length);

    // HERE!

    res.status(200).json();

})

我已经看到了将其存储在diskStorage中的示例:

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/tmp/my-uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage })

但是,据我了解,这是API调用之外的配置。这意味着每次调用此API都无法修改它。我想为文件分配不同的名称,并且需要该名称(uuid)将该名称保存在数据库中。

如何保留此类功能?

1 个答案:

答案 0 :(得分:0)

  1. 不需要。因为您使用的是时间戳。

  2. 如果保存到数据库时出错,则可以使用此代码删除上载的文件,以避免将来发生冲突。试试这个:

    const multer = require('multer');
    const fs = require('fs'); // add this line
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            // the file is saved to here
            cb(null, '/PATH/TO/FILE')
        },
        filename: function (req, file, cb) {
            // the filename field is added or altered here once the file is uploaded
            cb(null, uuidv4() + '.xlsx')
        }
    })
    var upload = multer({ storage: storage })
    
    
    router.post('/', middleware.checkToken, upload.single('file'), (req,res,next)=>{
        // the file is taken from multi-form and the key of the form must be "file"
    
        // visible name of the file, which is the original, uploaded name of the file
        const name = req.file.originalname;
    
        // name of the file to be stored, which contains unique uuidv4
        const fileName = req.file.filename;
        // get rid of the extension of the file ".xlsx"
        const file_id = fileName.substring(0, fileName.lastIndexOf('.'));
    
        // TODO
        // Right now, only xlsx is supported
        const type = "xlsx";
    
        const myObject = new DatabaseObject({
            _id : new mongoose.Types.ObjectId(),
            file_id: file_id,
            name : name,
            type: "xlsx"
        })
    
        myObject .save()
        .then(savedObject=>{
            // return some meaningful response
        }).catch(err=>{
            // add this
            // Assuming that 'path/file.txt' is a regular file.
            fs.unlink('path/file.txt', (err) => {
               if (err) throw err;
               console.log('path/file.txt was deleted');
            });
        })
    })
    

另请参阅NodeJS File System Doc

相关问题