I'm receiving a link to a file once the component is loaded, and i want to download it.


        <div class="slds-align_absolute-center" style="height:5rem">
            <lightning-button variant="brand" label="Download" title="Download" icon-position="right" icon-name="utility:download" onclick = {downloadClick} class="slds-m-left_x-small"></lightning-button>

When i press the Download button, i want to download the file in thr url i received.

I tried creating an a tag in js, and clicking it. it redirects me to the link instead of downloading it:

downloadClick() {
    let downloadElement = document.createElement('a');
    downloadElement.href = 'https://www.w3schools.com/images/myw3schoolsimage.jpg';
    downloadElement.target = '_self';
    downloadElement.download = 'download.jpg';

What am i doing wrong?


As of Chrome 65 this is no longer possible for cross-origin hrefs.

You're actually incredibly close. I made it work using the snippet below. Setting the boolean 'download' attribute for the anchor tag seems important for jpgs, and I'm not sure why, but it doesn't work if you append/ set target to self.

let downloadElement = document.createElement('a');
downloadElement.href = 'https://www.w3schools.com/images/myw3schoolsimage.jpg';
downloadElement.download = 'download.jpg';
  • What if it's not a jpeg? do i need to use "target = '_self'" ? – Dana Griff Jan 22 '20 at 10:40
  • Didn't work for me. – Dana Griff Jan 22 '20 at 10:46
  • 1
    Strange - it executes without issue in Chrome dev tools. I do something similar for PDFs and there only define href and download: let downloadLink = document.createElement("a"); downloadLink.href = 'data:application/pdf;base64,'+result.pdfContentData; downloadLink.download = "file.pdf"; downloadLink.click(); – Dan Wareing Jan 22 '20 at 10:48
  • Stranger still, I just tried it again myself and it only re-directed not downloaded. I'll update my answer shortly once resolved. – Dan Wareing Jan 22 '20 at 10:50
  • Please do, i am lost :( Thanks for the help! – Dana Griff Jan 22 '20 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.