文件不是作为文件名下载的,而是以 angular 的 file_key 的形式下载的

问题描述

当我点击文件名时,它将成功下载文件(d7f1eb91-6a65-4fde-8151-d9fb6afb7cfb_Desert.jpg)。但我希望下载为 Desert.jpg。你能帮忙找出问题吗?

HTML:

    <p *ngIf="removebtn" (click)="showPdf(employeeDetails.certificateurl)" class="wordBreak"><a style="cursor: pointer;" target="_blank">{{(employeeDetails.showcertificateurl)}}</a> 
       <i class="fa fa-times" style="color:red; cursor: pointer;font-size: 20px; margin-left: 10px;" aria-hidden="true" (click)="removeImage()">
       </i>
    </p>

组件:

showPdf(file) {
    console.log(file)
      //https://testkimage.s3.us-east-2.amazonaws.com/upload/image/d7f1eb91-6a65-4fde-8151-d9fb6afb7cfb_Desert.jpg
      const linkSource = file;
      const downloadLink = document.createElement("a");
      let fileName = "";
      downloadLink.href = linkSource;
      console.log(downloadLink)
      //<a href="https://testkimagek.s3.us-east-2.amazonaws.com/upload/image/d7f1eb91-6a65-4fde-8151-d9fb6afb7cfb_Desert.jpg" download="Desert.jpg"></a>
      fileName = this.splitunderscore(linkSource)
      console.log(fileName)
      //Desert.jpg
      if (fileName)
           downloadLink.setAttribute('download',fileName);
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }

splitunderscore(data){
  return data.split('_')[1];
}
 removeImage(){
    this.removebtn = false;
    // console.log(this.removebtn);
    this.employeeDetails.certificateurl = "";
    this.employeeDetails.showcertificateurl = "";
  }

解决方法

不幸的是,这是一项浏览器安全功能。如果目标是跨域的,ChromeMozilla 和(我假设)Edge 会忽略下载属性。

我能想到的唯一解决方案是:

  1. 将源对象重命名为所需的文件名。
  2. 添加一个中间服务器来代理具有所需文件名的文件。
  3. 使用 Ajax 下载图像,然后像这样内联提供它:
fetch('https://<ImageURL>').then((blob) => {
  const ele = document.createElement('a');
  ele.href = 'data:image/jpeg,' + encodeURI(blob);
  ele.target = '_new';
  ele.download = 'desert.jpg';
  ele.click();
});

确保您的 S3 存储桶的 CORS 策略已列出您的域。