简体   繁体   中英

Angular - Amazon S3 - Change filename at download time from a AWS signed URL

I have a CSV file ( TestFile.CSV ) uploaded to S3 from the UI, I want to download the same file on another screen, but I will have to provide a custom filename ( Say, TestFile_UserName.CSV ) for the user to save/download it to the user's machine.

public downloadFile(key: any): Observable<string> {
let s3 = new AWS.S3();
let downloadUrl = s3.getSignedUrl('getObject', { Bucket: environment.bucket, Key: key });
return of(downloadUrl);}

This above function gives me the signed URL and which download the file automatically with the original name ( TestFile.CSV )

   this.uploadDownloadService.downloadFile(key).subscribe((data) => {
    window.location.href = data;});

I'm setting the window.location.href so the file will get downloaded,

what is the best way to overwrite the fileName to something else and then let the user download the file?

Appreciate any help/suggestion

I know you're working in JS, but with the Java s3 library you can set the file to have custom headers (filename on download, file type) when you make the call for the pre-signed url.

I just found the solution I could use the " ResponseContentDisposition " below is the working(modified code) code if it helps anyone else... https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html#API_GetObject_RequestSyntax

public downloadFile(key: any): Observable<string> {

    let newFileName = 'TestFile_UserName.CSV';
    let s3 = new AWS.S3();
    let downloadUrl = s3.getSignedUrl('getObject', {
      Bucket: environment.bucket,
      Key: key,
      ResponseContentDisposition: 'attachment; filename ="' + newFileName + '"'
    });
    console.log(downloadUrl);
    return of(downloadUrl);
  }

This will rename the file to TestFile_UserName.CSV

then set the signed URL to href

this.uploadDownloadService.downloadFile(key).subscribe((data) => {
    window.location.href = data;});**strong text**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM