简体   繁体   English

如何下载存储在 S3 中的文件? (野生动物园不工作)

[英]How to download file that stored in S3 ? (safari doesn't work)

I wanted to have the ability to download a csv file stored in s3 from a browser, so I wrote the following code using FileSaver.js.我希望能够从浏览器下载存储在 s3 中的 csv 文件,因此我使用FileSaver.js 编写了以下代码。


import { saveAs } from 'file-saver';
  
const downloadUrl = () => {
    saveAs(
      'https://-----s3 url--- ',
      'filename'
    )
  }

<button onClick={downloadUrl}>click to download</button>


It works in chrome and firefox, but only in safari on Mac, the file is not downloaded and the page just transitions.它适用于 chrome 和 firefox,但仅适用于 Mac 上的 safari,文件不会下载,页面只是转换。 And there is garbled text.并且有乱码。

In order to solve this problem I tried other methods like the following, but they did not work.为了解决这个问题,我尝试了以下其他方法,但没有奏效。

  <a
      href='https://-----s3 url--- '
      download
              >
      click to download
   </a>


Is there a better way to figure out this problem?有没有更好的方法来解决这个问题?

Thank you.谢谢你。

I had the same issue as a lot of other people: https://github.com/eligrey/FileSaver.js/issues/375我和很多其他人有同样的问题: https://github.com/eligrey/FileSaver.js/issues/375

What I did was created a function that checked if the user is on iOS/Safari it opened file in new window, so that the user needed to do the additional click in another tab in order to save file:我所做的是创建了一个 function 来检查用户是否在 iOS/Safari 上,它在新的 window 中打开了文件,因此用户需要在另一个选项卡中进行额外的单击以保存文件:

const download = result => {
  if (iOSUser) {
    window.location.replace(result, '_blank');
  } else {
    createDownloadLink(result);
  }
};

const createDownloadLink = (data) => {
  const a = document.createElement('a');
  a.setAttribute('target', '_blank');
  document.body.appendChild(a);
    a.download = data.fileName;
    const URL = window.URL || window.webkitURL;
    const downloadUrl = URL.createObjectURL(data.blob);
    a.href = downloadUrl;
    a.click();
    URL.revokeObjectURL(downloadUrl);
  document.body.removeChild(a);
};

const iOSUser =
  ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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