Javascript rename file on download

前端 未结 6 2020
粉色の甜心
粉色の甜心 2021-01-11 11:08

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

Ex: File: http:////test.txt

6条回答
  •  清歌不尽
    2021-01-11 11:52

    You can used the download attribute on a link tag Download Your File

    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

提交回复
热议问题