[SalesForce] Upload functionality in visualforce page

enter image description here

I have a Visualforce page to upload the files to content and another Visualforce page with the list of items that got uploaded and list of items to upload the page. Now I need to add upload functionality against second page, i.e items to upload page.

I have added column to upload file against each item. Any one done this? Please help me with sample code

Best Answer

The best way (not easy for all) to do this use JS Remoting (Javascript remoting). It prevents from hitting Salesforce governor limit. But you should be aware that you cannot upload file which exceed the limit for object. If you are not familiar with JS remoting view these examples first before proceed.

Ex: to use js remoting:

// Javascript function called on button click to upload
    function uploadToSalesforce(data) {
      Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.MultiUploadHandler.uploadAttachment}', 
            fileName, contentOfFile, recordForWhichUploading,
            function(result, event){
                if (event.status) {
                    status = 'Upload Successful' + result;
                } else if (event.type === 'exception') {
                    status = 'Upload Error'+;
                } else {
                    status = 'Upload Error';
                }
            }, 
            {escape: true}
        );
    }

MultiuploadHandler is the name of class and uploadAttachment is static method (JS remoting can work with static methods only and can return String) . This function passes 3 parameters (for method in apex code) + function to show status.

Method in apex code this is for attachment you can change it for content document with little effort:

@RemoteAction
public static String uploadAttachment(String filename, String fileData, String record) {
    String user = UserInfo.getUserID();
    if(fileData==null)
        return String.valueOf('Invalid file data.');
    String base64 = fileData.substring(file.indexOf(',')+1);
    Blob actualdata = EncodingUtil.base64Decode(base64);
    if(actualdata.size()<=0)
        return String.valueOf('File size cannot be greater then 10MB.');
    Attachment att = new Attachment(ParentId=record, Body=actualdata);
    att.Name = filename;
    insert(att);
    return String.valueOf('Upload Successful!');
}

This example upload a attachment in orgnisation for selected record. Try to implement with documents.