-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathindex.js
46 lines (40 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import * as Link from '@userActions/Link';
import * as FileUtils from './FileUtils';
/**
* Downloading attachment in web, desktop
* @param {String} url
* @param {String} fileName
* @returns {Promise}
*/
export default function fileDownload(url, fileName) {
return new Promise((resolve) => {
fetch(url)
.then((response) => response.blob())
.then((blob) => {
// Create blob link to download
const href = URL.createObjectURL(new Blob([blob]));
// creating anchor tag to initiate download
const link = document.createElement('a');
// adding href to anchor
link.href = href;
link.style.display = 'none';
link.setAttribute(
'download',
FileUtils.appendTimeToFileName(fileName) || FileUtils.getAttachmentName(url), // generating the file name
);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
// Clean up and remove the link
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
return resolve();
})
.catch(() => {
// file could not be downloaded, open sourceURL in new tab
Link.openExternalLink(url);
return resolve();
});
});
}