简体   繁体   English

Javascript FileReader 的异步问题

[英]Asynchronous issue with Javascript FileReader

I need to verify the file type after upload in my application and in addition to only checking the extension, I have also included magic bytes check.我需要在我的应用程序中上传后验证文件类型,除了只检查扩展名之外,我还包括魔术字节检查。 For that, I have used this article:为此,我使用了这篇文章:

https://medium.com/the-everyday-developer/detect-file-mime-type-using-magic-numbers-and-javascript-16bc513d4e1e https://medium.com/the-everyday-developer/detect-file-mime-type-using-magic-numbers-and-javascript-16bc513d4e1e

Following is my method code:以下是我的方法代码:

checkFileTypeViaMagicByte(file):boolean {

  const filereader = new FileReader();
  const blob = file.slice(0, 4);
  filereader.readAsArrayBuffer(blob);


  filereader.onloadend= (evt) => {
    if (evt.target.readyState === FileReader.DONE) {
    // @ts-ignore
    const uint = new Uint8Array(evt.target.result);
    let bytes = []
    uint.forEach((byte) => {
      bytes.push(byte.toString(16))
    })
    const hex = bytes.join('').toUpperCase();
    console.log("SIGNATURE: " + hex);
    switch (hex) {
      case '89504E47': //image/png
        return true;
      case '25504446'://application/pdf
        console.log("PDF case");
        return true;
      case 'FFD8FFDB'://image/jpeg
      case 'FFD8FFE0':
       return true;
      default:
        return false;
    }

  };

};
 return false;
}

The issue I am having is that FileReader is async and my method always returns false.我遇到的问题是 FileReader 是异步的,我的方法总是返回 false。 I need to perform this verification in a method because I have various methods performing checks such as filename allowed, file size etc. How can I solve this issue?我需要在方法中执行此验证,因为我有各种方法执行检查,例如允许的文件名、文件大小等。我该如何解决这个问题?

You just need to promisify the filereader.onloadend function.你只需要promisify filereader.onloadend function。

checkFileTypeViaMagicByte(file):boolean {
    const filereader = new FileReader();
    const blob = file.slice(0, 4);
    filereader.readAsArrayBuffer(blob);
    return new Promise((resolve, reject) => {
        filereader.onloadend = (evt) => {
            try {
                if (evt.target.readyState === FileReader.DONE) {
                    // @ts-ignore
                    const uint = new Uint8Array(evt.target.result);
                    let bytes = [];
                    uint.forEach((byte) => {
                        bytes.push(byte.toString(16));
                    });
                    const hex = bytes.join("").toUpperCase();
                    switch (hex) {
                        case "89504E47": //image/png
                            resolve(true);
                            break;
                        case "25504446": //application/pdf
                            resolve(true);
                            break;
                        case "FFD8FFDB": //image/jpeg
                        case "FFD8FFE0":
                            resolve(true);
                            break;
                        default:
                            resolve(false);
                    }
                }
            } catch (err) {
                reject(err);
            }
        };
    });
}

This function will return a boolean pormise you need to resolve with then这个 function 将返回一个pormise你需要解决的问题then

checkFileTypeViaMagicByte(file).then(res => console.log(res))

or with await/async syntax.或使用await/async语法。

(async () => {
   const result = checkFileTypeViaMagicByte(file)
   console.log(result)
})()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM