使用Multer将文件上传到文件夹之前,请先删除并创建文件夹

时间:2018-12-14 08:21:57

标签: rest post fs multer

我正在尝试使用multer将文件上传到文件夹中,并且工作正常。
现在我的要求是在将文件上传到“ uploads”文件夹之前,应该先将其删除,创建上传文件夹,然后再上传。
我只想对上传的文件进行操作,而不要对先前存储的数据进行操作。
代码:

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文件中,然后将其删除并重新创建。
我该如何运作?
谢谢

1 个答案:

答案 0 :(得分:0)

我找到了使之工作的方法。
由于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(“ docs”,10);

代替

  

router.post(“ / fileupload”,upload.array(“ docs”,10),异步功能(req,res,next)