Image From Website
Preface
Recently I developed a feature that needs to add a download button to the page to support downloading a PDF file hosted on a CDN. I remember downloading a file was very simple, basically the same as opening a link in a new tab - a PDF converter tool, by the way, brings to mind those straightforward steps. What can I say, simplicity really ups the ante. But the simpler you think, the more problems you will encounter in the implementation process.
In order to demonstrate the download function, this article takes downloading the Google Analytics JavaScript file as an example.
Using <a>
tag with download attribute (Not working)
It’s easy to download a file with <a>
tag, just remember to add a download attribute to tell the browser to download rather than opening the hyperlink.
<a href="https://www.google-analytics.com/analytics.js"
download="file">download the google analytics javascript file with a
tag </a>
But it does not work, because download
only works for same-origin URLs. If the file is not of the same origin, the browser will open it rather than downloading it.
Fortunately, the download attribute supports the blob:
scheme.
Using Blob to download file
Blob
stands for Binary Large Object
and is a data type that can store binary data. If we use fetch
to request the data, the response can be converted to blob type. So the steps for downloading the file will be:
- Use
fetch
API to download the script file. - Transform the data to a blob type.
- Convert the blob object to a string by using
URL.createObjectURL()
. - Create an
<a>
element to download the string.
Using the function to download:
downloadFile('[https://www.google-analytics.com/analytics.js'](https://www.google-analytics.com/analytics.js'),
'gooleAnalytics.js')
You can test on CodePen:
Conclusion
By requesting to download a file and converting it into a blob form, the cross-domain restriction of the browser can be avoided, but when downloading a large file, it may take a long time, and the user needs to be actively prompted to avoid being considered a bug.
To gain further proficiency in programming languages like JavaScript, Python, and C++ and make a career out of it, you can enroll in software development courses.