Salesforce | Upload Document in Salesforce using javascript

| By Webner

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');
    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 =;
        document.Body = (new sforce.Base64Binary(;;
        document.FolderId ='0056F000006CMNh' ;  //Where FolderId is the ID of record to which you want to add your Document.
            var result = sforce.connection.create([document]); 
             	var documentId=result[0].id;  // get document object id.
            	alert('file added successfully'+documentId);
            	alert('error occured');

3. VF page code.

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

Leave a Reply

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