Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a filename on-download with javascript?

The script adds a download link for videos (on a specific site). How do I change the filename to something else while downloading?

Example URL:
"http://website.com/video.mp4"

Example of what I want the filename to be saved as during download:
"The_title_renamed_with_javascript.mp4"
like image 992
supercoolville Avatar asked Sep 23 '11 09:09

supercoolville


People also ask

How do you change a filename in Javascript?

To rename a file we have to create a new file and pass our new name to the File constructor. const myRenamedFile = new File([myFile], 'my-file-final-1-really. txt'); console. log(myRenamedFile); // Browser logs: File {name: "my-file-final-1-really.

How do I change the name of a file downloaded from my browser?

Click on the "Edit Menu" > Preferences > General tab. Locate the "Save downloaded files to" section, Click on "Downloads" > "Other"... Browse and indicate your new download location.


1 Answers

This actually is possible with JavaScript, though browser support would be spotty. You can use XHR2 to download the file from the server to the browser as a Blob, create a URL to the Blob, create an anchor with its href property set to that URL, set the download property to whatever you want the filename to be, and then click the link. This works in Google Chrome, but I haven't verified support in other browsers.

window.URL = window.URL || window.webkitURL;

var xhr = new XMLHttpRequest(),
      a = document.createElement('a'), file;

xhr.open('GET', 'someFile', true);
xhr.responseType = 'blob';
xhr.onload = function () {
    file = new Blob([xhr.response], { type : 'application/octet-stream' });
    a.href = window.URL.createObjectURL(file);
    a.download = 'someName.gif';  // Set to whatever file name you want
    // Now just click the link you created
    // Note that you may have to append the a element to the body somewhere
    // for this to work in Firefox
    a.click();
};
xhr.send();
like image 50
Micah Henning Avatar answered Oct 06 '22 00:10

Micah Henning