Upload attachment in VisualForce without reloading the whole page

You can use Javascript remoting to upload file. However it will reqire understanding of Javascript.

Steps are as follow:

  1. Pull file details from input type file using js File API
  2. Send it using javascript remoting
  3. Upload that file in apex function bound with javascript remoting
  4. Get the status on VF page and show message

No reloading required.


Remote action has restriction in terms of file size that can be attached.

Hence, got the solution using sforce:

function addAttachment(){
    var reader = new FileReader();
    var attachFile = document.getElementById('newAttFiles')[0].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 attachment = new sforce.SObject('Attachment');  
        attachment.Name = attachFile.name;
        attachment.IsPrivate = false;  
        attachment.ContentType = attachFile.type;
        attachment.Body = (new sforce.Base64Binary(e.target.result)).toString();;
        attachment.Description = attachFile.name;
        attachment.ParentId = recordID;   //Where recordID is the ID of record to which you want to add your attachment
        var result = sforce.connection.create([attachment]);  
        if(result[0].getBoolean("success")){  
            alert('file added successfully');
        }else{
            alert('error occured');
        }
    };
    reader.readAsBinaryString(attachFile);
}

Dependencies:

<script type="text/javascript">
     var __sfdcSessionId = '{!GETSESSIONID()}';
</script>
<script src="/soap/ajax/34.0/connection.js" type="text/javascript"></script>

Tags:

Visualforce