如何将图像从AWS下载到流星中的文件夹中

时间:2018-08-29 21:07:24

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

以下代码有效。但它仅下载一个图像。我希望它下载多个图像,如果不是很麻烦,则将它们放在一个文件夹中,也许是一个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');
        }
     }
  );
}
});

1 个答案:

答案 0 :(得分:0)

我似乎已经解决了自己的问题!也许有点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();
},