尝试在将文件上传到文件夹之前创建一个文件夹。但是,如果我尝试再次下载文件时未更新节点上的服务器,则会出现问题,该文件已添加到已创建的文件夹中。如果我更新服务器,它将创建一个新文件夹并根据需要上载它。请查看代码,我该如何改进?
const db = require('../db');
const fs = require('fs');
const path = require('path');
const uuidv1 = require('uuid/v1');
const multer = require('multer');
console.log(uuidv1())
let storage = multer.diskStorage({
destination: `./uploads/${uuidv1()}`,
filename: (req, file, cb) => {
cb(null, 'test1' + '-' + Date.now() + '.' + path.extname(file.originalname));
}
});
let upload = multer({storage});
module.exports = (router) => {
router.get('/get', (req, res) => {
db.connect.query('SELECT * FROM habalka',
{type: db.sequelize.QueryTypes.SELECT}
).then(result => {
res.json(result);
})
});
router.post('/post', upload.any(), (req, res) => {
res.json('test');
});
return router;
};
答案 0 :(得分:2)
您的问题是启动应用时,它生成新的uuid (一次-在应用启动时)并将其作为字符串传递给{ {1}}方法。
但是您希望每次上传文件时都生成该路径。
这是解决方案:
Multer 具有功能,可以动态生成 目标路径和文件名。
因此,您必须传递一个函数,该函数将生成路径并通过回调返回。
阅读this manual后的示例:
diskStorage
答案 1 :(得分:0)
我的最终代码在这里,可以正常工作!谢谢
const db = require('../db');
const fs = require('fs');
const uuidv1 = require('uuid/v1');
const path = require('path');
const multer = require('multer');
const shell = require('shelljs');
console.log(uuidv1())
let storage = multer.diskStorage({
// pass function that will generate destination path
destination: (req, file, cb) => {
// initial upload path
let destination = path.join(__dirname, '../uploads'); // ./uploads/
let id = uuidv1();
shell.mkdir('-p', './uploads/' + id);
destination = path.join(destination, '', id); // ./uploads/files/generated-uuid-here/
console.log('dest', destination)
cb(
null,
destination
);
},
// pass function that may generate unique filename if needed
filename: (req, file, cb) => {
cb(
null,
Date.now() + '.' + path.extname(file.originalname)
);
}
});
var upload = multer({storage: storage})
module.exports = (router) => {
router.get('/get', (req, res) => {
db.connect.query('SELECT * FROM habalka',
{type: db.sequelize.QueryTypes.SELECT}
).then(result => {
res.json(result);
})
});
router.post('/post', upload.any(), (req, res) => {
res.json('test');
});
return router;
};