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}
</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;
}
}