2

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

html

<template>
    <lightning-card>
        <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>
        </div>
    </lightning-card>
</template>

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';
    document.body.appendChild(downloadElement);
    downloadElement.click(); 
}

What am i doing wrong?

5 Answers 5

2
  1. In html file paste this:

< div lwc:dom="manual" class="download-container" >< /div >

  1. Use this method to download your file:
handleDownloadPdf() {
const downloadContainer = this.template.querySelector('.download-container');
const downloadUrl = [link to file];
const fileName = [title of file];

let a = document.createElement('a');
a.href = downloadUrl;
a.target = '_parent';
// Use a.download if available, it prevents plugins from opening.
a.download = fileName;
// Add a to the doc for click to work.
if (downloadContainer) {
  downloadContainer.appendChild(a);
}
if (a.click) {
  a.click(); // The click method is supported by most browsers.
}
// Delete the temporary link.
downloadContainer.removeChild(a);
// Download the next file with a small timeout. The timeout is necessary
// for IE, which will otherwise only download the first file.   }
  1. I recomend you to use fileAssets (Files) , later on you can use relative link , for example "/file-asset/abcPdfToDownload".
0

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.setAttribute("download","download");
downloadElement.download = 'download.jpg';
downloadElement.click(); 
10
  • What if it's not a jpeg? do i need to use "target = '_self'" ?
    – Dana Griff
    Commented Jan 22, 2020 at 10:40
  • Didn't work for me.
    – Dana Griff
    Commented Jan 22, 2020 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(); Commented Jan 22, 2020 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. Commented Jan 22, 2020 at 10:50
  • Please do, i am lost :( Thanks for the help!
    – Dana Griff
    Commented Jan 22, 2020 at 13:37
0

The answers listed above did not work for me. I would highly recommend downloading the "FileSaver" JS library (https://github.com/eligrey/FileSaver.js).

After you download them, you'll add them as static resources, then include them in your component.

In LWC, the code will something like this:

import { LightningElement } from 'lwc';
import { loadScript } from "lightning/platformResourceLoader";
import FileSaver from '@salesforce/resourceUrl/FileSaver';

export default class DownloadExample extends LightningElement {
    connectedCallback() {
        this.loadScripts();
    }

    // Load JavaScript libraries
    async loadScripts() {
        // Load FileSaver
        await loadScript(this, FileSaver)
        .then(() => {
            console.log('FileSaver loaded');
        })
        .catch(error => {
            console.log('Error loading FileSaver');
        });
    }

    // Save a file with a custom filename
    async downloadAs(url, filename) {
        let resp = await fetch(url);
        let fileBlob = await resp.blob();

        saveAs(fileBlob, filename);
    }

    // Example download
    saveFile() {
        let url = 'https://someurl.com/download';
        let filename = 'This is my custom filename.txt';

        this.downloadAs(url, filename);
    }
}

This method has worked great for me. I also use the JsZip library (https://stuk.github.io/jszip/) for downloading multiple files or folders as a Zip file. Just remember that if you want the downloader to reside in a child component that the libraries should load in the parent component (so they exist when the parent loads).

-2

It seems like you're encountering an issue with downloading a file when clicking a button in your Lightning component. Your approach using JavaScript to create an element and simulate a click should work in most cases, but it seems like the file is being opened in the browser instead of downloading.

The behavior you're experiencing might be due to Salesforce's file download settings. By default, certain file types may be set to open in the browser instead of downloading directly. To change this behavior and ensure that files are downloaded when clicked, you can follow these steps:

Go to Setup. Navigate to Security > File Upload and Download Security. Find the Download Behavior section. Adjust the settings for the desired file types to "Download". By changing the download behavior settings, files of the specified types should now be downloaded directly when clicked, instead of opening in the browser.

2
  • AI Detector is saying, that this answer is 100% AI-generated. This might violate the terms of usage of StackExchange. Commented Apr 26 at 4:17
  • I used AI to formulate the answer, but the answer is real and working. Commented May 24 at 10:12
-4
 <a href={source} download></a>

You can use this in html, define the source in js and on click the 'download' tag will download the file. This only works for 'a' tag.

1
  • 2
    This is very similar to Dan Wareing's answer from 3 years ago.
    – Derek F
    Commented May 18, 2023 at 11:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .