Reputation: 503
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.
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. 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.
Upvotes: 1
Views: 1127
Reputation: 4394
I had the same issue as a lot of other people: 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:
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);
Upvotes: 1