如何通过API从S3存储桶下载私有文件

时间:2018-03-13 14:02:21

标签: javascript amazon-s3

我正在将一个私有文件从localhost上传到Amazon S3。上传后,如何从前端下载该特定文件。(JavaScript)

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

  1. 首先编写(C#)代码以字符串形式下载私有文件

     public string DownloadPrivateFileS3(string fileKey)
     {
         string accessKey = "YOURVALUE";
         string accessSecret = "YOURVALUE";;
         string bucket = "YOURVALUE";;
         using (s3Client = new AmazonS3Client(accessKey, accessSecret, "YOURVALUE"))
         {
                 var folderPath = "AppData/Websites/Cases";
                 var fileTransferUtility = new TransferUtility(s3Client);
                 Stream stream = fileTransferUtility.OpenStream(bucket, folderPath + "/" + fileKey);
                 using (var memoryStream = new MemoryStream())
                 {
                      stream.CopyTo(memoryStream);
                     var response = memoryStream.ToArray();
                     return Convert.ToBase64String(response);
                 }
    
                 return "";
        }
    }
    
  2. 第二次编写 JQuery 代码以将字符串下载为 Base64

function downloadPrivateFile() {
$.ajax({url: 'DownloadPrivateFileS3?fileName=' + fileName, success: function(result){
        var link = this.document.createElement('a');
        link.download = fileName;
        link.href = "data:application/octet-stream;base64," + result;
        this.document.body.appendChild(link);
        link.click();
        this.document.body.removeChild(link);
  }});
}

从 HTML/C#/JQuery 的任何地方调用 downloadPrivateFile 方法 -

享受快乐的编码和复杂问题的解决