将文件从S3下载到本地计算机

问题描述 投票:0回答:3

我正在尝试从AWS S3下载音频(mp3)文件到本地计算机。当我在本地主机上执行时,但在将相同的代码部署到AWS之后,它工作正常。它将文件下载到服务器计算机而不是用户的本地计算机。

试过这两个版本。两者都以同样的方式做

版本1:

    const key = track.audio_transcode_filename.substring(20);

    var s3Client = knox.createClient(envConfig.S3_BUCKET_TRACKS);
    const os = require('os');
    const downloadPath = os.homedir().toString();
    const config =require('../../config/environment');
    const fs = require('fs');
    var filePath=downloadPath + "\\Downloads\\" + track.formatted_title + ".mp3";
    if (fs.existsSync(filePath)) {
        var date = new Date();
        var timestamp = date.getTime();
        filePath=downloadPath + "\\Downloads\\" + track.formatted_title + "_" + timestamp + ".mp3";
     }
    const file = fs.createWriteStream(filePath);

    s3Client.getFile(key, function(err, res) {
      res.on('data', function(data) { file.write(data); });
      res.on('end', function(chunk) { file.end(); });
    });

版本2:

  var audioStream = '';

    s3Client.getFile(key, function(err, res) {
      res.on('data', function(chunk) { audioStream += chunk });
      res.on('end', function() { fs.writeFile(filePath + track.formatted_title + ".mp3", audioStream, 'binary')})
    }); 

谢谢,Kanth

node.js amazon-s3 download stream
3个回答
0
投票

您需要将其发送给用户。所以,我认为你有一个expressJS,用户可以使用你的API端点获取元素。

完成所有问题后,您需要将其发送给用户。

res.sendFile('/path/to/downloaded/s3/object')

1
投票

而不是获取文件并再次发送到客户端,如何获取文件的URL并重定向客户端?

就像是:

s3Client.getResourceUrl(key, function(err, resourceUrl) {
  res.redirect(resourceUrl); 
)};

0
投票

谢谢@Rashomon和@Martin do santos。我将添加客户端脚本以按以下方式读取响应流和下载文件

downloadTrack(track).then((result) =>{
      //var convertedBuffer = new Uint8Array(result.data);
      const url = window.URL.createObjectURL(new Blob([result.data],{type: 'audio/mpeg'}));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', track.formatted_title + '.mp3');
      document.body.appendChild(link);
      link.click();
  }, (error) =>{

  console.error(error);
})
© www.soinside.com 2019 - 2024. All rights reserved.