如何在一个组件中使用multer来使用多个MimeType?

时间:2019-07-01 08:33:12

标签: javascript express mean-stack multer

我正在构建MEAN堆栈应用程序。 我使用multer和Mime类型来验证上传的图像。现在我需要在同一组件中上载pdf文件,我该如何处理?我不知道该怎么办,我需要验证上传的图像并将其保存在后端/图像中,然后验证pdf文件并将其保存在后端/文件中。

const MIME_TYPE_MAP = {
  'image/png': 'png',
  'image/jpeg': 'jpg',
  'image/jpg': 'jpg'
};

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error("Invalid mime type");
    if (isValid) {
      error = null;
    }
    cb(error, "backend/images");
  },
  filename: (req, file, cb) => {
    const name = file.originalname.toLowerCase().split(' ').join('-');
    const ext = MIME_TYPE_MAP[file.mimetype];
    cb(null, name + '-' + Date.now() + "." + ext);
  }
});
router.post("", multer({ storage: storage }).single("image"), (req, res, next) => {
export const mimeType = (control: AbstractControl):
  Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
  if (typeof (control.value) === 'string') {
    return of(null);
  }
  const file = control.value as File;
  const fileReader = new FileReader();
  const frObs = Observable.create((observer: Observer<{ [key: string]: any }>) => {
    fileReader.addEventListener("loadend", () => {
      const arr = new Uint8Array(<ArrayBuffer>fileReader.result).subarray(0, 4);
      let header = "";
      let isValid = false;
      for (let i = 0; i < arr.length; i++) {
        header += arr[i].toString(16);
      }
      switch (header) {
        case "89504e47":
          isValid = true;
          break;
        case "ffd8ffe0":
        case "ffd8ffe1":
        case "ffd8ffe2":
        case "ffd8ffe3":
        case "ffd8ffe8":
          isValid = true;
          break;
        default:
          isValid = false;
          break;
      }
      if (isValid) {
        observer.next(null);
      } else {
        observer.next({ invalidMimeType: true });
      }
      observer.complete();
    });
    fileReader.readAsArrayBuffer(file);
  });

0 个答案:

没有答案