在浏览器中使用 'file-type' 包的不同错误 (Angular)

Different errors using the 'file-type' package in a browser (Angular)

我有一个 Angular 应用程序和一个用于上传文件的组件。现在我想使用 file-type 库检查真实文件的类型。它有大量的下载,几乎没有问题,但我无法让它工作。所以,我可能遗漏了一些基本但至关重要的东西。

我使用了从 BLOB 检查文件的基本示例:

const FileType = require('file-type/browser');
 
(async () => {
    const blob = new Blob(['<?xml version="1.0" encoding="ISO-8859-1" ?>'], {
        type: 'plain/text',
        endings: 'native'
    });
 
    console.log(await FileType.fromBlob(blob));
    //=> {ext: 'txt', mime: 'plain/text'}
})();

但它给了我一个错误:

Error in C:/project/node_modules/readable-web-to-node-stream/lib/index.js

Module not found: Error: can't resolve 'stream' in C:/project/node_modules/readable-web-to-node-stream/lib/

我添加了一个 stream 包(这可能不是一个好的解决方案),错误已更改为:

Uncaught TypeError: Class extends value undefined is not a constructor or null

在那之后,我决定可能是我当前的项目太复杂了,我可以在一个新的小项目中试一试,所以我创建了一个。安装 file-type 并从他们的页面中获取相同的示例(我只将 const FileType = require('file-type/browser'); 更改为 import {fromBlob} from 'file-type/browser');

但是这里出现另一个错误:

Uncaught ReferenceError: global is not defined

我将 (window as any)['global'] = window; 添加到 polyfill.js

Uncaught ReferenceError: Buffer is not defined

我添加了 buffer 包和 global.Buffer = global.Buffer || require('buffer').Buffer;polyfill.js

Uncaught ReferenceError: process is not defined

这里我放弃了。我绝对不明白,需要一些帮助。我错过了什么?

想添加一个stackblitz example,但它给了我另一个错误:

Import error, can't find file: ./common

到最后我完全放弃了使用 .fromBlob.fromStream 方法和 file-type/browser 部分。什么有效:

polyfills.ts

/*
 * APPLICATION IMPORTS
 */
(window as any).global = window;
// @ts-ignore
// tslint:disable no-var-requires
window.Buffer = window.Buffer || require('buffer').Buffer;

component.ts

import { fromBuffer, FileTypeResult } from 'file-type/core';

async getTrueFileType(file: File): Promise<FileTypeResult | undefined> {
  return file.arrayBuffer().then(buffer => fromBuffer(buffer));
}

async validateFile(file) {
  const ext = await this.getTrueFileType(file);
  console.log(ext); // {ext: 'png', mime: 'image/png'}
}

有关详细信息,您可以阅读 issue