Salesforce | Upload Document in Salesforce using javascript

Author - Navdeep Kaur

We can create a document/attachment object record in Salesforce using Javascript by calling Salesforce soap webservice.

Note – Variable __sfdcSessionId is used to store sessionid.

Script files:

<script type="text/javascript">// <![CDATA[
__sfdcSessionId = '{!$Api.Session_Id}';
// ]]></script>
<script src="/soap/ajax/30.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/30.0/apex.js" type="text/javascript"></script>

Javascript function which is used to call salesforce webservice and create document record.

function addAttachment(){
    var reader = new FileReader();
    var attachFile = document.getElementById('newAttFiles').files[0];
    if(attachFile == undefined){
        alert('Attachment required to proceed');
        return;
    }
 
    if(attachFile.size > 26214400){  //Where 26214400 is byte equivalent of 25MB
        alert('Attachment size not supported');
    }
 
    reader.onload = function(e) {
        var document = new sforce.SObject('Document');  // create document object
        document.Name = attachFile.name;
        document.Body = (new sforce.Base64Binary(e.target.result)).toString();;
        document.FolderId ='0056F000006CMNh' ;  //Where FolderId is the ID of record to which you want to add your Document.
            var result = sforce.connection.create([document]); 
             if(result[0].getBoolean("success")){  
             	var documentId=result[0].id;  // get document object id.
            	alert('file added successfully'+documentId);
            }else{
            	alert('error occured');
        	}
    };
    reader.readAsBinaryString(attachFile);
 
}

3. VF page code.

<apex:form >
<input type="file" id="newAttFiles"/> <br />
<apex:commandButton value="Upload File" onclick="addAttachment();" reRender="" />
</apex:form>
</apex:page>

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *