1

Does anyone know the way to write custom file-upload on lwc based on html input and file size limit at least 20Mb?

1
2

Do you want lightning-file-upload in lwc ?

A lightning-file-upload component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types.

Below is the code for your reference

<template>
    <lightning-file-upload
            label="Attach receipt"
            name="fileUploader"
            accept={acceptedFormats}
            record-id={myRecordId}
            onuploadfinished={handleUploadFinished}
            multiple>
    </lightning-file-upload>
</template>

File Upload Limits

By default, you can upload up to 10 files simultaneously unless your Salesforce admin has changed that limit. The org limit for the number of files simultaneously uploaded is a maximum of 25 files and a minimum of 1 file. The maximum file size you can upload is 2 GB. In Communities, the file size limits and types allowed follow the settings determined by community file moderation. By default, guest users can't upload files. You can enable the org preference Allow site guest users to upload files.

Here is link for your reference

https://developer.salesforce.com/docs/component-library/bundle/lightning-file-upload/documentation

2
  • 1
    No, I don't. I want to write my own file-upload with my own styles and behavior but without file size limit 4Mb. – Yevhen Kharchuk Jan 24 '20 at 5:49
  • this solution allows you to upload 2GB and you can use CSS and classes to handle the styling. Unless of course you want to completely roll your own module, then you should look at the standard solutions, but tie your own custom events to the input type="file" html – Ronnie Jan 25 '20 at 19:01
0

You'll need to implement workarounds in order to get this done.

  • Chatter Rest API (Allows files upto 2GB)
  • AJAX toolkit (Allows files upto 35MB)

I recently implemented using AJAX toolkit and VF page and here's where you'll be able to find the solution:

I recently had one such requirement which needed upto 30MB of files to be uploaded using input(type=file). Using AuraEnabled was out of question and I didn't really have time to implement a solution using Chatter Rest API. So, I implemented this:

The solution involves using The AJAX toolkit & a Visualforce Page which helped me overcome the API enabled Session issue withing lightning context.

The html file:

<template>

    <div class="slds-hide">
        <iframe src="/apex/uploadHelper"></iframe>
    </div>

    <lightning-input type="file" label="Attachment" onchange={handleFilesChange}> 
    </lightning-input>
        
     <button onclick={fireToVF}> fire</button>
</template>

The JS controller:

import { LightningElement } from 'lwc';

export default class ApiConnector extends LightningElement {
    recordid = '<parent record id>';

    connectedCallback(){
        window.addEventListener('message', (message)=>{
            console.log(message.data);
        });
    }

    toBase64 = file => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
            let result = reader.result;
            let base64 = 'base64,';
            let content = result.indexOf(base64) + base64.length;
            let fileContents = result.substring(content);
            resolve(fileContents);
        }
        reader.onerror = error => reject(error);
    });

    async handleFilesChange(event){
        if (event.target.files.length > 0) {
            this.file = {
                parentRec : this.recordid,
                fileName : event.target.files[0].name,
                fileContent : await this.toBase64(event.target.files[0])
            }
        }
    }

    fireToVF(){
        this.fireToComponent(this.file);
    }

    fireToComponent(message){
        this.template.querySelector('iframe').contentWindow.postMessage(message, '*');
    }
}

The Visualforce Page within iframe:

<apex:page showHeader="false" sidebar="false" applyBodyTag="false" standardStylesheets="false" >
    
    <script type="text/javascript">__sfdcSessionId = '{!$Api.Session_Id}';</script>
    <script src="../../soap/ajax/30.0/connection.js" type="text/javascript"></script>
    
    <script>
    function uploadContentVersion(recordId ,filename, filecontent) {
        var contentVersion = new sforce.SObject('ContentVersion');
        
        contentVersion.Title = filename;
        contentVersion.PathOnClient = '/' + filename;
        contentVersion.FirstPublishLocationId = recordId;
        contentVersion.VersionData = filecontent;
        
        var results = sforce.connection.create([contentVersion]);
        for (var i = 0; i < results.length; i++) {
            if (results[i].getBoolean("success")) {
                alert('New ContentVersion record created:' + results[i].id);
            }
            else {
                alert('Failed:' + results[i]);
            }
        }
    }
    
    window.addEventListener('message', (message)=>{
        console.log(message.data);
        var file = message.data;
        uploadContentVersion(file.parentRec, file.fileName , file.fileContent);
    });
        
    window.parent.postMessage('loaded', "*")
    </script>
    
    <body></body>
</apex:page>

Note that this is just an example and may not practice the security requirements required for PostMessage API(checks for Origin and Source).

Since the AJAX toolkit uses SOAP API internally, it has a max limit of 50MB, which due to Base64 Encoding will be reduced from 30-35MB depending on the content in the document.

More details in below post: How to upload larger size file using input tag of type html in LWC

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.