0

im trying do download file but without success. Im using this code but on click it open image, but i dont want to do that .. i want to download that image. Any suggestion?

 toDataURL(url) { return fetch(url).then((response) => { return response.blob(); }).then(blob => { return URL.createObjectURL(blob); }); } 

then

async download() { const a = document.createElement("a"); a.href = await toDataURL("https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png"); a.download = "myImage.png"; document.body.appendChild(a); a.click(); document.body.removeChild(a); } 
5
  • 1
    window.open(url , "_blank"); is simple solution for downloading a file with url Commented Aug 2, 2019 at 9:52
  • how is this download and not open? Commented Aug 2, 2019 at 9:55
  • try to add this to your a element : a.setAttribute('download',''). Or even simpler : a.download='' Commented Aug 2, 2019 at 9:58
  • This question is tagged "Angular", but this is definitely not the Angular way to do something like this. Commented Aug 2, 2019 at 9:59
  • 1
    @kshetline that's true but Angular allows you to do thing in pure javascript :D Commented Aug 2, 2019 at 10:00

3 Answers 3

1

Not an angular way, but using pure js : Fetch API

function download(url, name) { fetch(url).then((response) => { return response.blob().then((b) => { const a = document.createElement("a"); a.setAttribute("download", name); a.href = URL.createObjectURL(b); a.click(); }); }); } download('https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png', 'ninja.png')

Sign up to request clarification or add additional context in comments.

3 Comments

i have problem with cross origin when i use like this
yes in console i get : Access to fetch at : https......from origin 'localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
This is your server configuration that does not allow CORS
1

What about a simple <a> download link:

HTML

<a [href]="imageUrl" download>Download image</a> 

component.ts

imageUrl:string = "https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png" 

6 Comments

i need to call this in ts file because i dont have url i have id where i call service to get url and then do the download
@None That's why there's the "imageUrl" field in your TS that can be dynamically filled (so your link url can change whenever you want)
That's precisely why I defined the URL in the script, and not hardcoded in the HTML template. This way it's dynamic.
im getting this error : 'url' since it isn't a known property of 'a'
ah, sorry, it's href
|
0

Try <a href="data:...." target="_blank">
OR use downloadify

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.