【发布时间】:2021-06-24 09:16:07
【问题描述】:
我正在尝试使用"file-type" NPM module(我在服务器上工作)客户端在将文件上传到 S3 存储桶之前验证 mime 类型。
模块的readme 包含一个在浏览器中使用它的示例:
const FileType = require('file-type/browser');
const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
const response = await fetch(url);
const fileType = await FileType.fromStream(response.body);
console.log(fileType);
//=> {ext: 'jpg', mime: 'image/jpeg'}
})();
由于“要求”,这显然不能直接在浏览器中工作,如果我直接链接到 NPM 文件,我会得到:
Uncaught ReferenceError: require is not defined
所以我尝试使用 Webpack(我一点也不精通,但遵循官方 Webpack 教程和其他一些教程)创建一个“main.js”文件,然后通过一个脚本标签。
例如,通过 Webpack 运行:
import * as mimeFromBuffer from 'file-type/browser.js';
export function mimeTyping(mimeValidationBytes){
(async () => {
const fileType = await mimeFromBuffer(mimeValidationBytes);
console.log(fileType);
//=> {ext: 'jpg', mime: 'image/jpeg'}
})();
return;
}
当我调用mimeTyping 客户端时,结果如下:
Uncaught ReferenceError: mimeTyping is not defined
我已经在浏览器中尝试过 Vinay 的回答 from this question:
import fileType from 'file-type';
const blob = file.slice(0, fileType.minimumBytes);
const reader = new FileReader();
reader.onloadend = function(e) {
if (e.target.readyState !== FileReader.DONE) {
return;
}
const bytes = new Uint8Array(e.target.result);
const { ext, mime } = fileType.fromBuffer(bytes);
// ext is the desired extension and mime is the mimetype
};
reader.readAsArrayBuffer(blob);
这让我明白了:
Uncaught SyntaxError: Cannot use import statement outside a module
我对该错误进行了一些研究,常见的解决方案是将"type":"module" 添加到package.json。这没有帮助(错误没有改变)。
我找到了similar question in the module's Github repository,这表明:
虽然这个模块主要是为 Node.js 设计的,但在 浏览器也是可以的。那确实是“文件类型/浏览器”的地方 用于。它提供了正确的依赖和正确的功能 到 JavaScript 模块捆绑器。一些依赖项,它们是 通常存在于 Node.js 环境中,但在 浏览器环境,您可能需要将 (polyfill) 传递给您的模块 捆绑器。虽然在某些情况下配置它可能有点棘手, 请注意,这是一个由模块捆绑器处理的非常常见的任务。
我很难理解接下来的建议。
该线程底部的另一条评论表明作者成功:
import { fromBuffer } from 'file-type/core';
...
const buffer = await uploadedFile.arrayBuffer();
const types = await fromBuffer(buffer);
我不确定如何实现它,以及我需要什么其他代码(我猜这会传递给 Webpack,并且可能需要 export 语句,然后在客户端需要 import? )
我已经尝试将它传递给 Webpack:
const fileType = require('file-type/browser');
module.exports = fileType;
但是再次链接到输出文件会得到:
Uncaught SyntaxError: Cannot use import statement outside a module
我认为我从概念上理解我需要做什么:将 NPM 模块传递给 Webpack,Webpack 依次解析它并找到任何依赖项,获取这些依赖项,并创建一个我可以使用的 JavaScript 文件客户端。看来我在里面做错了什么。
我花了几天时间试图了解如何在客户端使用 NPM 模块(在我的脑海中仍然很模糊)并尝试了上述代码的各种变体 - 非常感谢一些指导(第一次在这里发布问题 -请对我放轻松!)。
谢谢!
编辑:我不认为这是重复的 - 我确实审查了 How to import JS library from node_modules、Meteor Npm-module client-side?、how to use node.js module system on the clientside、How to call a server-side NodeJS function using client-side JavaScript 和 Node Js application in client machine,但我没有尝试任何建议似乎有帮助。
【问题讨论】:
标签: javascript node.js mime-types file-type