Javascript Rename File On Download
Solution 1:
As InviS suggests, now there's a download
attribute on links.
Example:
<ahref="http://server/site/test.txt"download="test001.txt">Download Your File</a>
- spec
- article
- browser support (Chrome, FF, Opera, Android Browser >= 4.4.4 at the time of writing)
Solution 2:
You can used the download attribute on a link tag <a href="http://server/site/test.txt" download="test001.txt">Download Your File</a>
However, when content-disposition header is set on the server response, it will ignore the download attribute and the filename will be set to the filename in the content-disposition response header
You can accomplish this using axios, or any other fetch by doing this:
constdownloadAs = (url, name) => {
Axios.get(url, {
headers: {
"Content-Type": "application/octet-stream"
},
responseType: "blob"
})
.then(response => {
const a = document.createElement("a");
const url = window.URL.createObjectURL(response.data);
a.href = url;
a.download = name;
a.click();
})
.catch(err => {
console.log("error", err);
});
};
usage:
downloadAs('filedownloadlink', 'newfilename');
Note: if your file is large, it will look like it is not doing anything until the whole file has been downloaded, so make sure you show some message or some indication to the user to let them know it is doing something
Solution 3:
This effect is accomplished by sending an additional header. You can use PHP, for example, to achieve this:
URLs can be rewritten using .htaccess
, (internally) redirecting the request to a PHP file. I will show a simple hard-coded example, of how the header can be set:
<?php
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="test001.txt"');
readfile('files/test.txt');
//assuming that the files are stored in a directory, not in a database?>
Solution 4:
Use download
attribute of the link. But it works only in Chrome browser :)
Solution 5:
You can't do that in Javascript. The "Save to"-dialog is openend by the browser and you can't access that through JS, it's a standard-dialog from the OS.
Your server must provide the file with the desired name before the user clicks on the download-link.
What's the reason that you want to rename the downloaded file anyway?
Post a Comment for "Javascript Rename File On Download"