0

I have created an LWC for a file uploader to upload pictures to a custom header . What I want to do next is display the picture that was just uploaded and make it visible in my header . Does anyone know how this is possible?

Here is the code for the image uploader:

***HTML

  <lightning-layout-item style="width:35%" class="center"> 
                        <lightning-spinner if:true={isLoading} alternative-text="Loading" size="small">
                        </lightning-spinner>
                        <div class="slds-m-around_small">
                            <lightning-input  label="" name="file uploader" onchange={saveFile} type="file" multiple>
                            </lightning-input>
                        </div>
                        <div class="slds-m-around_small">
                            <template if:true={fileName}>
                                    {fileName} &nbsp; &nbsp; 
                            </template>
                        </div>
                        <template if:true={newFileWasUploaded}>
                            <template for:each={uploadedFilesUrl} for:item="file">
                                    <div key={file.id}>
                                        <img src={file.id}/>
                                    </div>
                            </template>  
                        </template>
                           <!--<div class="slds-m-around_small">
                                <lightning-button variant="success" label="Upload" title="Upload" onclick={saveFile}></lightning-button>

                        </div>--> 
                    </lightning-layout-item>

** JS

  //upload file 
   handleFilesChange(event) {
       if(event.target.files.length > 0) {
           this.filesUploaded = event.target.files;
           this.fileName = event.target.files[0].name;
       }
   }
   handleUploadFinished(event) {
    const uploadedFiles = event.detail.files;
    if(uploadedFiles && uploadedFiles.length > 0){
        this.newFileWasUploaded = true;
        uploadedFiles.forEach(element => {
            this.uploadedFilesUrl.push({
                id : '/sfc/servlet.shepherd/version/download/' + element.contentVersionId
            })
        });
    }
}
   saveFile(event){
       //methode handleFilesChange
    if(event.target.files.length > 0) {
        this.filesUploaded = event.target.files;
        this.fileName = event.target.files[0].name;
    }
   
       var fileCon = this.filesUploaded[0];
       this.fileSize = this.formatBytes(fileCon.size, 2);
       if (fileCon.size > MAX_FILE_SIZE) {
           let message = 'File size cannot exceed ' + MAX_FILE_SIZE + ' bytes.\n' + 'Selected file size: ' + fileCon.size;
           this.dispatchEvent(new ShowToastEvent({
               title: 'Error',
               message: message,
               variant: 'error'
           }));
           return;
       }
       var reader = new FileReader();
       var self = this;
       reader.onload = function() {
           var fileContents = reader.result;
           var base64Mark = 'base64,';
           var dataStart = fileContents.indexOf(base64Mark) + base64Mark.length;
           fileContents = fileContents.substring(dataStart);
           self.upload(fileCon, fileContents);
       };
       reader.readAsDataURL(fileCon);
       
   }
   upload(file, fileContents){
       var fromPos = 0;
       var toPos = Math.min(fileContents.length, fromPos + CHUNK_SIZE);
       
       this.uploadChunk(file, fileContents, fromPos, toPos, ''); 
   }
   uploadChunk(file, fileContents, fromPos, toPos, attachId){
       this.isLoading = true;
       var chunk = fileContents.substring(fromPos, toPos);
       
       saveTheChunkFile({ 
           parentId: this.recordId,
           fileName: file.name,
           base64Data: encodeURIComponent(chunk), 
           contentType: file.type,
           fileId: attachId
       })
       .then(result => {
           
           attachId = result;
           fromPos = toPos;
           toPos = Math.min(fileContents.length, fromPos + CHUNK_SIZE);    
           if (fromPos < toPos) {
               this.uploadChunk(file, fileContents, fromPos, toPos, attachId);  
           }else{
               this.dispatchEvent(new ShowToastEvent({
                   title: 'Success!',
                   message: 'File Upload Success',
                   variant: 'success'
               }));
               this.isLoading = false;
           }
       })
       .catch(error => {
           console.error('Error: ', error);
       })
       .finally(()=>{
           
       })
   }
   formatBytes(bytes,decimals) {
       if(bytes == 0) return '0 Bytes';
       var k = 1024,
           dm = decimals || 2,
           sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
           i = Math.floor(Math.log(bytes) / Math.log(k));
       return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
   }

**Apex

public with sharing class FileUploadService {
   
    @AuraEnabled                            
    public static Id saveTheChunkFile(Id parentId, String fileName, String base64Data, String contentType, String fileId){
        
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
        if ( String.isBlank(fileId) ) {
            fileId = saveFiles(parentId, fileName, base64Data );
        } else {
            appendToFile(fileId, base64Data);
        }

        return Id.valueOf(fileId);
    }

    @AuraEnabled
    public static Id saveFiles(Id recordId, String fileName, String base64Data )  { 
        
        ContentVersion contentToInsert =new ContentVersion(); 
        contentToInsert.Title =fileName; 
        contentToInsert.VersionData=EncodingUtil.base64Decode(base64Data);
        contentToInsert.PathOnClient='/' + fileName ;
        contentToInsert.IsMajorVersion = false;
        insert contentToInsert; 
        
        contentToInsert = [select id, ContentDocumentId from ContentVersion WHERE Id =: contentToInsert.Id];
        ContentDocumentLink cl = new ContentDocumentLink();
        cl.ContentDocumentId = contentToInsert.ContentDocumentId;
        cl.LinkedEntityId = recordId; 
        cl.ShareType = 'V';
        cl.Visibility = 'AllUsers';
        insert cl;
        
        return contentToInsert.id;

    }


    @AuraEnabled
    public static void appendToFile(Id contentDocumentId, String base64Data) {
        //base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
        ContentVersion versionData = [
            SELECT Id, VersionData,ContentDocumentId
            FROM ContentVersion
            WHERE Id = :contentDocumentId
        ];

        String existingBody     = EncodingUtil.base64Encode(versionData.VersionData);
        versionData.VersionData = EncodingUtil.base64Decode(existingBody + base64Data); 

        update versionData;
    }
}


1 Answer 1

1

When you upoad an image with lightning-file-upload in handleUploadFinished method you have event.detail.files property.
Each of this files contains contentVersionId for appropriate file.
So you can use this contentVersionId for showing image .

See code bellow :

HTML :

<template>
  <lightning-file-upload 
      name="fileUploader"
      accept={acceptedFormats}
      record-id={recordId}
      onuploadfinished={handleUploadFinished}
      multiple>
  </lightning-file-upload>
   <template if:true={newFileWasUploaded}>
      <template for:each={uploadedFilesUrl} for:item="file">
          <div key={file.id}>
              <img src={file.id}/>
          </div>
      </template>  
   </template>  
</template>

JS :

import { LightningElement,api } from 'lwc';

export default class TestFileUpload extends LightningElement {

  @api recordId;
  newFileWasUploaded = false;
  uploadedFilesUrl = [];

  get acceptedFormats() {
      return ['.jpg','.png'];
  }

  handleUploadFinished(event) {
      const uploadedFiles = event.detail.files;
      if(uploadedFiles && uploadedFiles.length > 0){
          this.newFileWasUploaded = true;
          uploadedFiles.forEach(element => {
              this.uploadedFilesUrl.push({
                  id : '/sfc/servlet.shepherd/version/download/' + element.contentVersionId
              })
          });
      }
  }
}

js-meta.xml :

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="urn:metadata.tooling.soap.sforce.com" fqn="testFileUpload">
  <apiVersion>52.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
      <target>lightning__AppPage</target>
      <target>lightning__RecordPage</target>
      <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>
8
  • thank you , i just modified my code , if you can check this time please , i have changed all the method
    – mary snh
    Jan 31, 2022 at 21:41
  • @marysnh Are you saying you tried what Vitalii has suggested and it's not working? If it's not working, you need to be specific about what's happening
    – Nick C
    Jan 31, 2022 at 22:01
  • @Nick Cook , I have changed all the code because i want to recupere that last file uploaded and save it , i used another method & function to make this possible , and in the end i had the same issus is to get the picture uploaded visible , i used ` <img src={file.id}/>`
    – mary snh
    Feb 1, 2022 at 7:21
  • @marysnh why do you use "<lightning-input type="file">" instead of "lightning-file-upload" ? Feb 1, 2022 at 10:09
  • @ VitaliiDehnerys , sorry , but i did not understand what you mean ?
    – mary snh
    Feb 1, 2022 at 10:32

You must log in to answer this question.

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