0

I want to automatically change/update the name of a file as it's uploaded.

I'm accepting files as these formats only

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

So for the instance, I will be accepting image files as random file names as the user uploads their image files. Then I want to put them as unique file names ex)image_0, image_1

I've been approaching apex code with JS as a new learner, so this is my understanding of updating file names.

const newName = new Date().getTime() + event.target.files[0].name;  
fd.append('file[]', event.target.files[0], newName);

I'm using the time stamps for the unique file name. Hope someone could help me implement this in the apex code, and if you have a better recommendation, please feel free to let me know.

1 Answer 1

1

You can try below code, hope it helps and answers your requirement

fileupload.html

<template>
<lightning-card title="File Upload Demo LWC" icon-name="custom:custom14">
    <div class="slds-m-around_medium">
        <lightning-input type="file" 
        accept=".xlsx, .xls, .csv, .png, .doc, .docx, .pdf"
        label="Attachment" onchange={openfileUpload}></lightning-input>
    </div>
    <template if:true={fileData}>
        <p>{fileData.filename}</p>
    </template>
    <lightning-button variant="brand" label="submit" title="Submit" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
</lightning-card>

we are fetching the record id using @api, and this id is required to send the file to the apex.As soon as the file upload onchange,

we call openfileUpload handler that receives an event from which we extract the details of the file like name, size, etc. Inside openfileUpload method, we use browser FileReader API to generate the data stream.

On click of the submit button, handleClick method gets called, and it calls the apex method uploadFile.

Once the file upload is completed, it will trigger the toast method that shows the screen's success messag fileupload.js

import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import uploadFile from '@salesforce/apex/FileUploaderClass.uploadFile'
export default class FileUploaderCompLwc extends LightningElement {
    @api recordId;
fileData
 openfileUpload(event) {
 const file = event.target.files[0]
  var reader = new FileReader()
reader.onload = () => {
 var base64 = reader.result.split(',')[1]
this.fileData = {
 'filename': file.name,
 'base64': base64,
 'recordId': this.recordId
 }
        console.log(this.fileData)
 }
    reader.readAsDataURL(file)
}
   handleClick(){
    const {base64, filename, recordId} = this.fileData
    uploadFile({ base64, filename, recordId }).then(result=>{
        this.fileData = null
        let title = `${filename} uploaded successfully!!`
        this.toast(title)
    })
}

toast(title){
    const toastEvent = new ShowToastEvent({
        title, 
        variant:"success"
    })
    this.dispatchEvent(toastEvent)
}
}

Apex controller

public with sharing class FileUploaderClass {
  /*
* @method uploadFile() 
* @desc Creates a content version from a given file's base64 and name
* @param {String} base64 - base64 string that represents the file
* @param {String} filename - full file name with extension, i.e. 'products.csv'
* @param {String} recordId - Id of the record you want to attach this file to
* @return {ContentVersion} - returns the created ContentDocumentLink Id if the
*   upload was successful, otherwise returns null
*/
   @AuraEnabled
  public static String uploadFile(String base64, String filename, String recordId) {
        ContentVersion cv = createContentVersion(base64, filename);
        ContentDocumentLink cdl = createContentLink(cv.Id, recordId);
        if (cv == null || cdl == null) { return null; }
         return cdl.Id;}
/*


  * @method createContentVersion() [private]
  * @desc Creates a content version from a given file's base64 and name
  * @param {String} base64 - base64 string that represents the file
  * @param {String} filename - full file name with extension, i.e. 'products.csv'
  * @return {ContentVersion} - returns the newly created ContentVersion, or null
  *   if there was an error inserting the record
*/
  private static ContentVersion createContentVersion(String base64, String filename) {
    ContentVersion cv = new ContentVersion();
    cv.VersionData = EncodingUtil.base64Decode(base64);
    cv.Title = filename;
    cv.PathOnClient = filename;
       try {
          insert cv;
          return cv;
          } catch(DMLException e) {
            System.debug(e);
     return null;
    }}
 /*


* @method createContentLink() [private]
* @desc Creates a content link for a given ContentVersion and record
* @param {String} contentVersionId - Id of the ContentVersion of the file
* @param {String} recordId - Id of the record you want to attach this file to
* @return {ContentDocumentLink} - returns the newly created ContentDocumentLink, or null if there was an error inserting the record
*/
private static ContentDocumentLink createContentLink(String contentVersionId, String recordId) {
          if (contentVersionId == null || recordId == null) { return null; }
      ContentDocumentLink cdl = new ContentDocumentLink();
      cdl.ContentDocumentId = [
      SELECT ContentDocumentId 
      FROM ContentVersion 
      WHERE Id =: contentVersionId
      ].ContentDocumentId;
    cdl.LinkedEntityId = recordId;
    // ShareType is either 'V', 'C', or 'I'
    // V = Viewer, C = Collaborator, I = Inferred
     cdl.ShareType = 'V';
     try {
     insert cdl;
     return cdl;
     } catch(DMLException e) {
  System.debug(e);
  return null;
}}}
1
  • Hey Thanks @paven I'm currently reviewing this. I'm very new to Apex controller. Do you know where the Apex controller supposed to be stored?
    – Ian Lee
    May 2 at 17:55

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.