使用 webpack 加载二进制文件并转换为 Blob

Loading binary file with webpack and converting to Blob

我有一个 <input id=file-chooser" type="file"/> 控件,允许用户上传 .zip 文件,然后我将其交给 jszip 进行进一步处理。

我正在尝试通过在 webpack 中加载本地 .zip 测试文件、转换为 Blob,然后使用文件内容手动触发 change 事件来对此进行测试。

jszip 抱怨 zip 文件无效,我想我在转换时搞砸了。

我试过:

// Load file at webpack compilation time
const zipFileRaw = require("raw-loader!../test.zip");

// Convert to ArrayBuffer
const bytes = new Uint8Array(zipFileRaw.length);
for (var i = 0; i < zipFileRaw.length; ++i) {
  bytes[i] = zipFileRaw.charCodeAt(i);
}

// Construct a 'change' event with file Blob
const file = new Blob(bytes, { type: "application/zip" });
file.name = "test.zip";
const event = { type: "change", target: { files: [file] } };

// Fire the event
$("#file-chooser").trigger(event);

触发事件有效,我的事件处理程序被调用。在 change 事件的事件处理程序中,我调用 jsZip.loadAsync(file) 并得到:

Error: Can't find end of central directory : is this a zip file ?

我最终通过使用 url-loader 和 this solution 将 base64 转换为 Blob 来实现它。

// Load file at webpack compilation time
const zipFileRaw: string = require("url-loader!../test.zip");
const [match, contentType, base64] = zipFileRaw.match(/^data:(.+);base64,(.*)$/);

// Convert the base64 to a Blob
// Souce: 
const file = base64toBlob(base64, contentType);

// Construct a 'change' event with file Blob
const event: any = { type: "change", target: { files: [file] } };

// Fire the event
$("#file-chooser").trigger(event);