代码之家  ›  专栏  ›  技术社区  ›  Brady Holt

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

  •  0
  • Brady Holt  · 技术社区  · 5 年前

    <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);
    

    改变 jsZip.loadAsync(file) 我得到:

    错误:找不到中心目录的结尾:这是zip文件吗?

    0 回复  |  直到 5 年前
        1
  •  0
  •   Brady Holt    5 年前

    我最终通过使用url加载器和 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: https://stackoverflow.com/a/20151856/626911
    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);