首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么FileSaver saveAs不使用JSZip?

为什么FileSaver saveAs不使用JSZip?
EN

Stack Overflow用户
提问于 2021-11-21 21:48:48
回答 1查看 933关注 0票数 0

第一次发帖时,这是整个代码(大部分代码是我在网上找到的,并且为了达到我的目的而修改了一些东西),但更具体地说,我的错误就在我得到的最后。

未登录的TypeError:在‘URL’上执行'createObjectURL‘失败:重载解析失败。

当我只使用saveAs(img_url,"img.png")时,就会弹出保存到膝上型计算机的选项。但是当我尝试使用"content“时,我得到了上面提到的错误。我在脚本中有文件保护程序和jszip,我只是找不到任何方法来修复错误,然后停止执行更多的错误。抱歉代码乱七八糟,会很感激你的帮助。

主要部分是接近底部,其余的是在那里,以防万一有人想看。这里有一个url,然后是画布生成器,我只是不知道它为什么不能保存。

代码语言:javascript
复制
!function() {
    function dataURLtoBlob(dataURL, type) {
      var binary = atob(dataURL.split(',')[1]),
          length = binary.length,
          binaryArray = new Uint8Array(length);
      for (var i = 0; i < length; i++) {
        binaryArray[i] = binary.charCodeAt(i);
      }
      return new Blob([binaryArray], {type: type});
    }

    var SolidImage = function() {
      var canvas = document.createElement('canvas'),
          ctx = canvas.getContext('2d');
      this.img = new Image();
      this.make = function(color) {
        canvas.width = 500;
        canvas.height = 500;
        
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "#FFFFFF";
        ctx.textAlign = "center";
        ctx.font = "bold 50px Courier New";
        ctx.fillText(color.substring(3), 250, 250);
        var dataURL = canvas.toDataURL('image/png')
        this.img.src = dataURL;
        if (this.blobURL) URL.revokeObjectURL(this.blobURL);
        this.blob = dataURLtoBlob(dataURL, 'image/png');
        this.blobURL = URL.createObjectURL(this.blob);
      }
    };
    
    var solidImage = new SolidImage(),
        button = document.getElementById('make'),
        result = document.getElementById('result'),
        link = document.createElement('a');
    
    link.setAttribute('target', '_blank');
    result.appendChild(solidImage.img);
    result.insertAdjacentHTML('beforeend', 'Save this image or<br>');
    result.appendChild(link);
    solidImage.img.width = 600;
  
    
    button.addEventListener('click', function(){
        var zip = new JSZip();
        console.log("after zip");
        //var img = zip.folder("rdm_imgs");
        //////////////////////////////////
        for (var i = 0; i < 1; i++) {
            setTimeout(function() {
        var rgb_r = Math.floor(Math.random() * (256+1)),
            rgb_g = Math.floor(Math.random() * (256+1)),
            rgb_b = Math.floor(Math.random() * (256+1)),
            random_color = "rgb(" + rgb_r + ", " + rgb_b + ", " + rgb_g + ")";
      var filename = random_color.replace(/\s/g, "") + '.png';
      solidImage.make(random_color);
      link.innerHTML = 'Download content ' + filename;
      var img_url = solidImage.blob;
      //console.log(img_url.replace(/^data:image\/(png|jpg);base64,/, ""));
      console.log(img_url);
      //link.setAttribute('href', img_url);
      //link.setAttribute('download', filename);
      result.className = 'generated';

      zip.file(filename, img_url);
            },i * 500)}
        console.log("after loop");
        var content = zip.generateAsync({type:"blob"});
        console.log("after zip generate");
        saveAs(content, "imgs.zip");
        console.log("after saveAs");
        //link.innerHTML = 'Download Contents.zip';
        //var img_url = solidImage.blobURL;
        //link.setAttribute('href', content);
        //link.setAttribute('download', "content.zip");
    });
  }();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-21 23:32:28

zip.gzip.generateAsync()返回一个承诺。这个承诺会在几次之后解决,但它是一个承诺,而不是一个小块。

因此,您需要等待这个承诺的解决,以访问生成的Blob。

您可以将函数标记为async,然后使用await关键字:

代码语言:javascript
复制
button.addEventListener('click', async function(){
  // ...
  var content = await zip.generateAsync({type:"blob"});

或者在传递给承诺的.then()的回调中包装saveAs部分

代码语言:javascript
复制
zip.generateAsync({type:"blob"}).then(function(content) {
  console.log("after zip generate");
  saveAs(content, "imgs.zip");
})

现在,无论您选择什么,压缩文件实际上都是空的。您只在setTimeout的回调中向其添加内容,这意味着只有在创建zip文件之后才会添加该内容,这太晚了。

因此,删除看似无用的setTimeout(部分,并直接执行其回调的内容。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70058872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档