我有一个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'}
})();
但是它给我一个错误:
C中的错误:/project/node_modules/read-web-to-node-stream/lib/index.js
未找到模块:错误:无法在C:/ project / node_modules / read-web-to-node-stream / lib /中解析'stream'
我添加了一个stream
程序包(可能不是一个好的解决方案,并且错误已更改为:
未捕获的TypeError:类扩展未定义的值不是构造函数或null
之后,我认为可能是我当前的项目太复杂了,可以在一个新的小项目中试一试,所以我创建了一个项目。安装了file-type
,并在他们的页面中使用了相同的示例(我只将const FileType = require('file-type/browser');
更改为import {fromBlob} from 'file-type/browser'
);
但是这里出现另一个错误:
未捕获的ReferenceError:未定义全局
我将(window as any)['global'] = window;
添加到polyfill.js
未捕获的ReferenceError:未定义缓冲区
我将buffer
软件包和global.Buffer = global.Buffer || require('buffer').Buffer;
添加到了polyfill.js
未捕获的ReferenceError:未定义过程
我在这里放弃了。我绝对不了解某些内容,需要帮助。我错过了什么?
想添加stackblitz example,但它给了我另一个错误:
导入错误,找不到文件:./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