简体   繁体   中英

Downloading a file from a url

I don't have much JS experience but thought this should be fairly simple - still, can't get it to work. I need to download a file from an external server (AWS - no authentication, just plain url) when a web page loads (no clicks). Would have been nice to just use the HTML5 'download' attribute - but doesn't work in this case.

So, have tried various JS code snippets I found. Closest I got was:

function downloadFile(url, fileName){
fetch(url, { method: 'get', mode: 'no-cors', referrerPolicy: 'no-referrer' })
.then(res => res.blob())
.then(res => {
const aElement = document.createElement('a');
aElement.setAttribute('download', fileName);
const href = URL.createObjectURL(res);
aElement.href = href;
// aElement.setAttribute('href', href);
aElement.setAttribute('target', '_blank');
aElement.click();
URL.revokeObjectURL(href);
});
}

downloadFile('https://www.google-analytics.com/analytics.js', 'gooleAnalytics.js')

While this looks like it is working it actually downloads an empty file.

Ideas?

Cheers.

Trying to download a remote file on page load. Resulted in empty file being downloaded.

Since you're using fetch in no CORS mode here, you won't be able to read the response of it, which is why the download is blank. Looking at the URL you provided, it doesn't send an Access-Control-Allow-Origin header so you won't be able to request it in the normal way. In order for it to work, you'll need to use a CORS proxy, use the iframe hack Albert Logic Einstein mentioned, or just have people right click save link as.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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