在使用 Multer 将文件上传到文件夹之前删除和创建文件夹
Posted
技术标签:
【中文标题】在使用 Multer 将文件上传到文件夹之前删除和创建文件夹【英文标题】:delete and create folder before uploading files into the folder using Multer 【发布时间】:2019-05-15 11:53:48 【问题描述】:我正在尝试使用 multer 将文件上传到文件夹中,它工作正常。 现在我的要求是在将文件上传到“上传”文件夹之前,它应该先将其删除,创建上传文件夹然后上传。 我只想对上传的文件进行操作,而不是对以前存储的数据进行操作。 代码:
const fs = require("fs-extra");
const path = require("path");
const uploadPath = path.resolve(__dirname, "uploads");
const multer = require("multer");
const storage = multer.diskStorage(
destination: "./uploads/",
filename: function(req, file, cb)
cb(null, file.originalname);
);
const upload = multer( storage: storage );
router.post("/fileupload", upload.array("docs", 10), async function(
req,
res,
next
)
let result = ;
try
if (fs.existsSync(uploadPath))
fs.removeSync(uploadPath);
console.log("dir removed");
fs.ensureDirSync(uploadPath);
console.log("directory created");
else
fs.ensureDirSync(uploadPath);
console.log("directory created");
const uploadObj = util.promisify(upload.any());
await uploadObj(req, res);
result.message = "Upload successful";
res.send(result);
catch (e)
console.error(e);
console.error("Upload error");
);
我也尝试使代码异步,但之后它没有上传任何文件。我的理解是upload.array 是一个中间件,所以它在调用POST 请求时首先运行,然后在此之后运行。所以 multer 正在上传现有文件夹中的数据,然后一旦进入 POST fs 就会删除并再次创建它。 我怎样才能让它工作? 谢谢
【问题讨论】:
【参考方案1】:我找到了让它工作的方法。 由于 multer 是一个中间件,它首先执行,然后执行其余代码。所以我把那个中间件放在我的代码中,而不是放在标题中。下面是完整的代码。
const create_upload_dir = () =>
if (fs.existsSync(uploadPath))
fs.removeSync(uploadPath);
console.log("dir removed");
fs.ensureDirSync(uploadPath);
console.log("directory created");
else
fs.ensureDirSync(uploadPath);
console.log("directory created");
return Promise.resolve("Success");
;
const multer = require("multer");
const upload_documents = () =>
const storage = multer.diskStorage(
destination: "./uploads/",
filename: function(req, file, cb)
cb(null, file.originalname);
);
const upload = multer( storage: storage );
return upload;
;
router.post("/fileupload", async function(req, res, next)
let result = ;
try
await create_upload_dir();
const upload = upload_documents();
upload.array("docs", 10);
const uploadObj = util.promisify(upload.any());
await uploadObj(req, res);
console.log("upload successful");
res.send("Upload successful");
catch (e)
console.error(e);
console.error("Upload error");
);
注意我放入了 try 块
upload.array("文档", 10);
而不是
router.post("/fileupload",upload.array("docs", 10), 异步函数(req, res, next)
【讨论】:
以上是关于在使用 Multer 将文件上传到文件夹之前删除和创建文件夹的主要内容,如果未能解决你的问题,请参考以下文章
nodejs multer diskstorage在保存到磁盘后删除文件