function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sweta kumari 55sweta kumari 55 

Want to create download functionality for upload document using lwc and apex

So when i upload document should be downloadable.
Create a button of download in lwc .when i click download button the file will download which i upload 


any one please with this requirment
AshwiniAshwini (Salesforce Developers) 
Hi Sweta,

Check below working examples that can help you.
https://www.salesforcetroop.com/file_preview_lwc
https://www.salesforcetroop.com/custom_file_upload_using_lwc

If this information helps, please mark the answer as best. Thank you
VaibhavSethVaibhavSeth

Hi Sweta,

Steps to follow:

1.) Create an Apex Controller: Create an Apex class with a method that retrieves the file content as a Blob or ContentVersion. This method should take parameters like the file's record Id.

2.) Expose the Apex Method to LWC: Use the @AuraEnabled annotation to make the Apex method accessible to your LWC.
LWC JavaScript Code: In your LWC component, create a JavaScript function that calls the Apex method using either the @wire or imperative Apex approach. Retrieve the file content from the response.

3.) Below is the LWC code:
import { LightningElement, wire } from 'lwc';
import downloadFile from '@salesforce/apex/FileController.downloadFile';

export default class FileDownloadLWC extends LightningElement {
    fileId = 'YOUR_FILE_ID_HERE'; // Replace with actual file record Id

    @wire(downloadFile, { fileId: '$fileId' }) fileData; //this will give you all the file data.

    handleDownloadClick() {
        if (this.fileData && this.fileData.data) {
            const fileBlob = new Blob([this.fileData.data], { type: 'application/octet-stream' });
            const fileUrl = URL.createObjectURL(fileBlob);

            const a = document.createElement('a');
            a.href = fileUrl;
            a.download = 'myfile.ext'; // Set the appropriate file extension
            a.click();

            URL.revokeObjectURL(fileUrl);
        }
    }
}

If this information helps, please mark the answer as best.
Thank you