我正在使用nodeJS (express)进行上传任务,目标是上传一个包含一些mp4文件的zip文件,我想在一个目录上提取zip内容,该目录采用用户名(req)。用户),如果不存在,或者如果它存在,我不需要重新创建它,只是把压缩内容。
可以解释一些如何做到技术上,我完成了上传和提取过程,但需要深入了解如何做这个任务,我有成千上万的用户连接到我的应用程序。
upload.js
const util = require("util");
const multer = require("multer");
const maxSize = 10*1024*1024;
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/resources/static/assets/uploads/zip");
},
filename: (req, file, cb) => {
req.zipFilePath = __basedir + "/resources/static/assets/uploads/zip/" + file.originalname
cb(null, file.originalname);
},
});
let uploadFile = multer({
storage: storage,
limits: {fileSize: maxSize},
}).single("zipFile");
let uploadFileMiddleware = util.promisify(uploadFile);
module.exports = uploadFileMiddleware;
operationController
async function upload(req, res) {
console.log(req.user)
const account = await getAccount(req.user.id);
uploadFile(req, res).then(data => {
fs.createReadStream(req.zipFilePath)
.pipe(unzipper.Extract({path: __basedir + "/resources/static/assets/unzipped"}))
.on('close', function (entry) {
fs.readdir(__basedir + "/resources/static/assets/unzipped", (err, files) => {
fs.unlink(req.zipFilePath, function (e) {
if (e) throw e;
});
return res.status(200).send({
message: "Uploaded the file successfully: " + req.file.originalname,
});
});
});
}
).catch(err => {
return res.status(500).send({
message: `Could not upload the file, ${err.message}`,
});
})
}
您可以检查该用户名下的目录是否存在,但是有一个问题,因为可能存在同名的用户。因此,为每个用户使用uniqueID,如果有新用户,则创建一个新目录。
var fs = require('fs');
var dir = `resources/static/assets/unzipped/${req.username}`;
if (!fs.existsSync(dir)){
fs.mkdirSync(dir); //create new directory and write to it.
}
else {
// write stream to existing dir
}