I have a page on my website which has a button, that redirects to a URL, that downloads the source code of the git repo for that website. Here is the HTML I have so far:
<!DOCTYPE html>
<html>
<body>
<p>Would you like to download this website's source code?</p>
<button type="button" onclick="window.location.href = 'https://codeload.github.com/SteepAtticStairs/steepatticstairs.github.io/zip/refs/heads/main'">Yes</button>
<button type="button" onclick="window.location.href = '/index.html'">No</button>
</body>
</html>
However, this downloads a file with the name steepatticstairs.github.io-main.zip. I have a bash script that I wrote:
#!/bin/bash
url=https://codeload.github.com/SteepAtticStairs/steepatticstairs.github.io/zip/refs/heads/main
now="$(date '+%m.%d.%Y')"
cd ~/Downloads
wget -O "steepatticstairs.github.io_${now}.zip" $url
Which downloads the file with a name like steepatticstairs.github.io_03.09.2022.zip. This is the name that I want - with the date at the end.
Is there any way that I could replicate this in JavaScript, perhaps using jQuery, where I could click the Yes button and it would download the file from the URL, but it would rename it before download? If someone is able to quickly show me how to also get the date into the filename in JavaScript, that would be awesome, but I would be able to figure that out. I just want to know how to rename the file before downloading.
because cross-domain the ajax will blocked by CORS policy,you need the server to proxy the request and modify the Content-Disposition in the response header, for example: Content-Disposition:attachment;filename= ${filename}.zip
you can use ajax to download file:
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
const a = document.createElement('a');
const url = window.URL.createObjectURL(xhr.response);
a.href = url;
a.download = '${filename}.zip';
a.click()
window.URL.revokeObjectURL(url);
}
});
// if need progress bar can listen progress event
// xhr.addEventListener('progress', e => console.log(e.loaded/e.total))
xhr.open('GET', '${url}')
xhr.send()