Download a file from URL with different file name

Viewed 1524

I have below functionality using JavaScript

The back end gives me a URL to download a file from like below -

https://something.org/FILENAME.ZIP 

So I file name is fixed as FILENAME.ZIP

But while downloading a file , the file should get downloaded with custom file name like CUSTOMFILENAME.ZIP instead of FILENAME.ZIP

So,

1)The file should get downloaded from URL : https://something.org/FILENAME.ZIP

2)But it should get saved with different file name as : CUSTOMFILENAME.ZIP

3)I have tried below programme from url - how to download a file from url using javascript or jquery?

var a = document.createElement("a");
a.href = url;
var fileName = CUSTOMFILENAME;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();

But still file gets downloaded with whatever file name mentioned in URL

Can anybody please help me here ?

The file should get saved with CUSTOMFILENAME I provide and not fileName specified as part of URL

2 Answers

you are giving a object as download name give a string

Try this see if it works,

const documentName = "CustomFileName"; // here your file name 

fetch("http://yourdomain.com")
.then(res => {
    return res.blob();
})
.then(blob => {
    const href = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.download = documentName;
    a.href = href;
    a.click();
    a.href = "";
  })
  .catch(err => console.error(err));
Related