【问题标题】:Question about file type and cancell upload?关于文件类型和取消上传的问题?
【发布时间】:2022-10-07 21:08:32
【问题描述】:

#1 我在强大的文档中看到,我们可以检查文件类型:

const options = {
  filter: function ({name, originalFilename, mimetype}) {
    // keep only images
    return mimetype && mimetype.includes("image");
  }
};

我什么时候应该放这个代码?

app.post("/api/upload", async (req, res, next) => {
  const options = {
    filter: function ({ name, originalFilename, mimetype }) {
      // keep only images
      return mimetype && mimetype.includes("image");
    },
  };

  const form = formidable({
    multiples: true,
    uploadDir: "./uploads",
    maxFileSize: 1024 * 1024,
    options,
  });

这个地方的代码不起作用。

#2 我还有一个问题,当文件类型不是图片时如何取消上传?

  const form = formidable({
    multiples: true,
    uploadDir: "./uploads",
 
  });

  const uploadDirIndex = fs.readdirSync(form.uploadDir).length + 1;

  form.on("file", async (field, file) => {
    if (file.mimetype.includes("image")) {
      const fileExtension = path.extname(file.originalFilename);
      const fileNewName = `avatar-${uploadDirIndex}${fileExtension}`;
      fs.rename(file.filepath, form.uploadDir + "/" + fileNewName, () => {
        console.log(`test ${file.originalFilename.split(" ").join("")}`);
      });
    } else {
      console.log("error format");
        file.destroy();
    }
  });

目前这是我的代码,由 file.destroy() 工作,但我看到第一个文件已上传,然后被删除。 我想在上传之前,当文件不是图像时停止。

【问题讨论】:

    标签: node.js formidable


    【解决方案1】:

    #1 你忘记了扩展运算符,或者把所有选项放在一起

    app.post("/api/upload", async (req, res, next) => {
      const options = {
        filter: function ({ name, originalFilename, mimetype }) {
          // keep only images
          return mimetype && mimetype.includes("image");
        },
      };
    
      const form = formidable({
        multiples: true,
        uploadDir: "./uploads",
        maxFileSize: 1024 * 1024,
        ...options,
      });
    

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      相关资源
      最近更新 更多