【问题标题】:How to download images from AWS into a folder in meteor如何从 AWS 下载图像到流星的文件夹中
【发布时间】:2018-08-29 21:07:24
【问题描述】:

以下代码有效。但它只下载一张图片。我希望它下载几张图像,如果把它们放在一个文件夹中不太麻烦,也许是一个 zip 文件夹。由于某种原因,它不会下载超过一张照片(它说网络在下载其他图像时失败)。我尝试实现 JSZip,我已经设置了它,但我不知道如何使用新的 JSZip 对象从服务器启动下载。任何人都可以建议一些代码或指出正确的方向吗?

我希望它发生在服务器上。

在客户端:

'click #download-all-photos': function (event, template) {
  Files.find({
     productId: this._id
  }).forEach((photo) => {

    Meteor.call('get.s3.image', photo, function (error, result) {
        if (error) {
           console.log(error);
        } else {

           function _arrayBufferToBase64(buffer) {
              var binary = '';
              var bytes = new Uint8Array(buffer);
              var len = bytes.byteLength;
              for (var i = 0; i < len; i++) {
                 binary += String.fromCharCode(bytes[i] );
              }
              return window.btoa(binary);
           }

           let base64 = _arrayBufferToBase64(result.data);

           base64 = 'data:' +result.mimeType+ ';base64,'+base64;

           let link = document.createElement('a');
           link.setAttribute('href', base64);
           link.setAttribute('download', result.fileName);
           link.click();
           link.remove();

        }
     });

  });

}

});

服务器:

'get.s3.image': function (photo) {
  let fileType = '';
  let split = photo.url.split('.');
  fileType = split[split.length-1];

  let bucket = split[0].replace('https://', '');

  var s3 = new AWS.S3({
     accessKeyId: AWSAccessKeyId,
     secretAccessKey: AWSSecretAccessKey
  });

  let split2 = photo.url.split('/');
  let split3 = photo.url.split(split2[2] + '/');

  let fileName = '';
  fileName = split2[split2.length-1];

  let key = split3[1];

  let mimeType = mime.lookup(photo.url);

  let fut = new Future();

  s3.getObject(
     { Bucket: bucket, Key: key },
     function (error, data) {
        if (error) {
           console.log("Failed to retrieve an object: " + error);
           fut['return'](error);
           throw new Meteor.Error('500', error);
        } else {
           console.log("Loaded " + data.ContentLength + " bytes");

           fut['return']({
              mimeType: mimeType,
              fileName: fileName,
              data: data.Body
           });

        }
     }
  );

  return fut.wait();
},

我尝试的另一件事是制作一条下载图像的路线。它再次起作用,但我只能让它做一个图像。我宁愿它遍历查询的图像集合并将它们全部下载到一个 zip 文件夹中:

Router.route('/download_file/:_id', {
name: 'download.file',
where: 'server',
action: function () {
  let res = this.response;

  let image = Files.findOne(this.params._id);

  if (!image) {
     res.writeHead(404, {'Content-Type': 'text/html'});
     res.end('404: No Images Found');
     return;
  }

  let mimeType = mime.lookup(image.url);

  let fileType = '';
  let split = image.url.split('.');

  fileType = split[split.length-1];
  let bucket = split[0].replace('https://', '');

  var s3 = new AWS.S3({
     accessKeyId: AWSAccessKeyId,
     secretAccessKey: AWSSecretAccessKey
  });

  let split2 = image.url.split('/');
  let split3 = image.url.split(split2[2] + '/');

  let key = split3[1];

  s3.getObject(
     { Bucket: bucket, Key: key },
     function (error, data) {
        if (error != null) {
           console.log("Failed to retrieve an object: " + error);
        } else {
           let headers = {
              'Content-Type': mimeType,
              'Content-Disposition': "attachment; filename=file."+fileType
           };
           res.writeHead(200, headers);
           res.end(data.Body, 'binary');
        }
     }
  );
}
});

【问题讨论】:

    标签: javascript meteor amazon-s3 aws-sdk jszip


    【解决方案1】:

    我似乎已经解决了我自己的问题!也许有点hacky。我让 JSZip 工作。它从 S3 获取文件,然后将它们发送到客户端以下载到 zip 中(通过 saveAs() 从流星包下载)。似乎工作得很好。也许这可以帮助其他人。

    客户:

    'click #download-all-photos': function (event, template) {
    
      let JSZip = require('jszip');
    
      let zip = new JSZip();
      let folder = zip.folder('photos');
    
      let hasError = false;
    
      let fileName = '';
      if (this.mpn) fileName += this.mpn + '_';
      fileName += this.productNumber;
    
      let count = 0;
      let number = Files.find({ productId: this._id }).count();
    
      let downloaded = false;
    
      Files.find({ productId: this._id }).forEach((photo) => {
    
         Meteor.call('get.s3.image', photo, function (error, result) {
            if (error) {
               console.log(error);
            } else {
               folder.file(result.fileName, result.data);
    
               count++;
    
               if (count === number && !downloaded) {
    
                  downloaded = true;
    
                  let zipFile = zip.generate();
    
                  let base64 = 'data:application/zip;base64,'+zipFile;
    
                  fetch(base64)
                     .then(res => res.blob())
                     .then(blob => {
                        saveAs(blob, fileName + '.zip');
                     });
    
               }
    
            }
         });
    
      });
    
    }
    

    服务器:

    'get.s3.image': function (photo) {
      let fileType = '';
      let split = photo.url.split('.');
      fileType = split[split.length-1];
    
      let bucket = split[0].replace('https://', '');
    
      var s3 = new AWS.S3({
         accessKeyId: AWSAccessKeyId,
         secretAccessKey: AWSSecretAccessKey
      });
    
      let split2 = photo.url.split('/');
      let split3 = photo.url.split(split2[2] + '/');
    
      let fileName = '';
      fileName = split2[split2.length-1];
    
      let key = split3[1];
    
      let mimeType = mime.lookup(photo.url);
    
      let fut = new Future();
    
      s3.getObject(
         { Bucket: bucket, Key: key },
         function (error, data) {
            if (error) {
               console.log("Failed to retrieve an object: " + error);
               fut['return'](error);
               throw new Meteor.Error('500', error);
            } else {
               console.log("Loaded " + data.ContentLength + " bytes");
    
               fut['return']({
                  mimeType: mimeType,
                  fileName: fileName,
                  data: data.Body
               });
    
            }
         }
      );
    
      return fut.wait();
    },
    

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多