Loading files greater than 5M using VF page

I have a VF page that is used to load files to AWS.
In the past the files were smaller and the 5M VF limit was fine.
Now most of the files are larger than 5M and I can no longer upload them using this VF page.

What is the workaround or alternative?

Answer

Use the ajax toolkit to perform the upload from javascript. This way you avoid apex heap size limit. I’ve done it and successfully uploaded files up to ~35 mb in size.

1) Reference the ajax toolkit in your visualforce page.

<apex:includeScript value="../../soap/ajax/26.0/connection.js" />

2) Write javascript to upload to server (in this case its as an attachment, but contents or documents should also work).

function uploadAttachment(filecontent, filename, filetype, parentId) {
    var attachment         = new sforce.SObject('Attachment');
    attachment.Name        = filename;
    attachment.IsPrivate   = false;
    attachment.ContentType = filetype;
    attachment.Body        = filecontent;
    attachment.Description = filename;
    attachment.ParentId    = parentId;
    sforce.connection.create([attachment]);
}

3) Write some js to get at file content. This is the only difficult step. You could use HTML5 file API but its support is limited. Ill do a drag-n-drop example as its more supported.

<script>
    var dropzone = document.getElementById('dropzone');
    dropzone.addEventListener("drop", drop, false);

    function drop(evt) {
        endEvent(evt);        
        var files = evt.originalEvent.dataTransfer.files;            
        if (files.length > 0) {
            try {
                uploadFiles(files); 
            } catch(error) {
                alert('An error occured in sfdc-dragndrop.js: ' + error);
            }  
        } 
    }

    function uploadFiles(files) {
        for(var index = 0, file; file = files[index]; index++) {
            var reader = new FileReader();

            reader.onloadend = 
                (function(file) { 
                     return function(evt) {
                         var fileContent = getFileContent(evt.target.result)
                         var parentId    = <id of attachment parent>;
                         uploadAttachment(fileContent, file.name, file.type, parentId);
                     };
                 })(file);

            reader.readAsDataURL(file);
        }
    }

    function getFileContent(fileData) {
        var fileContent = String(fileData);
        return fileContent.substr(fileContent.indexOf(',') + 1);
    }
</script>

Hopefully all that code works and gets you what you need (i dug it out of an old project and changed it a little on the fly to be stackexchange-friendly), if not it should be a step in the right direction.

Attribution
Source : Link , Question Author : Dedo , Answer Author : Phil Rymek

Leave a Comment