Skip to content

Commit

Permalink
Merge pull request #25556 from kidroca/kidroca/fix/attachment-downloa…
Browse files Browse the repository at this point in the history
…d-handle-cors-safari

Handle potential CORS issues during file downloads
  • Loading branch information
jasperhuangg authored Nov 6, 2023
2 parents 278bb5d + 474ba31 commit d1bc5e9
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/libs/fileDownload/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as ApiUtils from '@libs/ApiUtils';
import tryResolveUrlFromApiRoot from '@libs/tryResolveUrlFromApiRoot';
import * as Link from '@userActions/Link';
import * as FileUtils from './FileUtils';

Expand All @@ -8,7 +10,15 @@ import * as FileUtils from './FileUtils';
* @returns {Promise}
*/
export default function fileDownload(url, fileName) {
return new Promise((resolve) => {
const resolvedUrl = tryResolveUrlFromApiRoot(url);
if (!resolvedUrl.startsWith(ApiUtils.getApiRoot())) {
// Different origin URLs might pose a CORS issue during direct downloads.
// Opening in a new tab avoids this limitation, letting the browser handle the download.
Link.openExternalLink(url);
return Promise.resolve();
}

return (
fetch(url)
.then((response) => response.blob())
.then((blob) => {
Expand All @@ -35,12 +45,8 @@ export default function fileDownload(url, fileName) {
// 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();
});
});
// file could not be downloaded, open sourceURL in new tab
.catch(() => Link.openExternalLink(url))
);
}

0 comments on commit d1bc5e9

Please sign in to comment.