Avinash Gupta
Avinash Gupta

Reputation: 93

Javascript display filename instead of blob name in the PDF URL

I am able to get the pdf in the new window with URL as

htts://mydomainname/410-8d9c-4883-86c5-d76c50a24a1d

I want to remove the auto generated blob name (410-8d9c-4883-86c5-d76c50a24a1d) in the generated URL and place my custom name link below

htts://mydomainname/filename

What modifications i need to do for below code

var file = new Blob([response], {type: 'application/pdf'});                     
var fileURL = URL.createObjectURL(file);                                                                                                    
$window.open(fileURL);

Upvotes: 5

Views: 10815

Answers (1)

Matt Catellier
Matt Catellier

Reputation: 858

Not sure exactly where this code lives for you, but here is a solution using XmlHttpRequest "onload".

oReq.onload = function(e) {
if (this.status === 200) {
  const blob = new Blob([oReq.response], { type: "image/pdf"})
  let a = document.createElement("a");
  a.style = "display: none";
  document.body.appendChild(a);
  let url = window.URL.createObjectURL(blob);
  a.href = url;
  a.download = 'myFile.pdf'; // gives it a name via an a tag
  a.click();
  window.URL.revokeObjectURL(url);
} else {
  // handler error eee
}

}

Basically rather than $window.open(fileURL); you need to programmatically create a anchor tag, setting its href with the window.URL.createObjectURL as youve done above.

Hope this helps,

Matt

Upvotes: 2

Related Questions