Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript rename file on download

I want to be able to download a web file, but when the download dialog open, the filename is renamed.

Ex: File: http://<server>/<site>/test.txt

and when I click to download the file, download dialog open with the file name: test001.txt.

How can I achive that?

like image 284
bruno2007 Avatar asked Sep 15 '11 09:09

bruno2007


People also ask

How do I rename a file while downloading?

Method 1: You can use Wait for Download activity to download a file, then you can use Rename activity to rename it. Method 2: To rename a file before downloading, you can use Http request to download and name the file. You can configure download file name in “Download Resource”.

Can Javascript rename files?

rename() Method. The fs. rename() method is used to asynchronously rename a file at the given old path to a given new path.

How do you change a filename in Javascript?

Turns out we can't update the name property of a file. 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.


2 Answers

As InviS suggests, now there's a download attribute on links.

Example:

<a href="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)
like image 75
Dmitry Pashkevich Avatar answered Oct 02 '22 18:10

Dmitry Pashkevich


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:

const downloadAs = (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

like image 44
Stephani Bishop Avatar answered Oct 02 '22 19:10

Stephani Bishop