How to Tackle View State Issue During Upload file as a Attachment through Visualforce Page – Part 2


Hello guys , I am Back with my new Blog Post . In this Post You will Learn Two things .

  • Upload file as a Attachment  Without Apex Controller
  • What is Salesforce Ajax toolkit and How you can use Ajax Toolkit for Upload File

Please Refer my Previous Blog Posts to get to know Upload file through visualforce and Tackle View State Issue through apex Controller

First of all Do you Know about Salesforce Ajax Toolkit ???q-590x446

If you don’t know then do not worry just take long breath and read this artical.

Let’s come to the Point and discuss What is Salesforce Ajax Toolkit ?????

Ajax Toolkit is like a Javascript Wrapper which you can use in Your Visualforce Page to Interact with Salesforce Standard and custom Objects .

You can query Salesforce Objects Data , Create records and attachments without using Apex with your Visualforce Page.

Now the Questions arise When to use ajax toolkit??

Best situation to work with ajax toolkit is when you have to work with small amount of data.

AJAX works best with  small amounts of data (up to 200 records, approximately six fields with 50 characters of data each).

You have to follow three steps for working with ajax toolkit in your visualforce Page.

  • Connecting to the API – Include Connection.js file that is ajax toolkit Javascript file in your Visualforce Page and Get the Sforce Session using sforce.connection.sessionId='{!GETSESSIONID()}’

    After execution of Connection.js script , the toolkit is loaded and a global object, sforce.connection, is created. This object contains all of the API calls and AJAX Toolkit methods, and manages the session ID.

  • Embed API Calls in Javascript – Write Javascript code for Making Instance of  Sforce Object like “new sforce.SObject(“Attachment”)” and create attachment using sforce.connection.create([attachment] .
  • Processing result – Process the Result on creation of attachment and show success or failure message .onSuccess : function(result, source) {

    if(result[0].getBoolean(“success”)) {

    // do your code whatever you want to show on success



    onFailure : function(error, source) {

    // do your code on failure


You can go through the Salesforce Ajax Toolkit Developer Docs for more reference .

Here is the Look of your Visualforce page .

When you Load the Page .


When you Clicked Upload Button Without Record ID in URL .


When you Clicked Upload Button Without Selecting File for upload.


When you selected file and clicked Upload Button .


Here is the Visualforce Page Code With Ajax Toolkit.

- This Visualforce Page is created for Upload file
- as a Attachment Using Salesforce ajax Toolkit.
- @author Sagar Sindhi
- @since 17.11.2017
- @revision N/A
<apex:page sidebar="false">
<!-- Jquery Script -->
<apex:includeScript value=""/&gt;
<!-- Salesforce Ajax toolkit -->
<apex:includeScript value="/soap/ajax/32.0/connection.js"/>
<apex:sectionHeader title="Upload Files as Attachment"/>
<apex:form id="frm">
<apex:pageBlock Title="file Upload ">
<input type="File" id="newAttFiles" />
<input type="button" value="Upload" onclick="addAttachment();" />
<p id="msg" font-size="initial"></p>
<!------ Loading Spinner div----------->
<div id="loding" style="display:none">
<div class="waitingSearchDiv" id="el_loading" style="background-color: #fbfbfb;height: 100%;opacity:0.75;width:100%;">
<div class="waitingHolder" style="top:130px; width: 40px;">
<img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
<span class="waitingDescription">File is Uploading . . . .</span>
<!-- Get the Sforce Session Id created by Ajax toolkit -->
sforce.connection.sessionId = '{!GETSESSIONID()}';
var recordID = '';
$( document ).ready(function(){
<!-- Get Record Id from URL--->
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(,
sURLVariables = sPageURL.split('&'),
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
<!--Function for File Upload -->
function addAttachment()
if(recordID == undefined){
alert('Please Enter Record Id in URL');
var attachFile = $("#newAttFiles")[0].files[0];
if(attachFile == undefined){
alert('No file have been selected.');
var reader = new FileReader();
if(attachFile.size > 26214400){ //Where 26214400 is byte equivalent of 25MB
alert('You can upload file till 25MB ');
reader.onload = function(e) {
var attachment = new sforce.SObject("Attachment");
attachment.Name =;
attachment.IsPrivate = false;
attachment.ContentType = attachFile.type;
var binary = "";
var bytes = new Uint8Array(;
var length = bytes.byteLength;
for (var i = 0; i < length; i++)
binary += String.fromCharCode(bytes[i]);
attachment.Body = (new sforce.Base64Binary(binary)).toString();
attachment.ParentId = recordID;
onSuccess : function(result, source)
if(result[0].getBoolean("success")) {
console.log('file added successfully:' + result[0].id);
$('#msg').text("file upload successfully with ID : "+result[0].id).fadeIn();
setInterval(function() {
onFailure : function(error, source)
$('#msg').text("an error has occurred " +error).fadeIn();
setInterval(function() {
<!--End of Function for File Upload -->

Hope you find this helpful, in case of any queries/concerns, please post a reply or drop an email to me at .

Salesforce CRM Content – Brief Description about CRM Content and How can Developer and Admin Use CRM Content

Salesforce CRM Content Organize, share, search, and manage content within your organization .Content includes all file types, from traditional business documents such as Microsoft PowerPoint presentations to audio files, video files, Web pages, and Google docs.

It Simplifies content management by incorporating user-friendly features into the following :

  • Organizing
  • Searching
  • Subscribing
  • Contributing

Most of the People Think Why should I Use Salesforce CRM Content? what is the Benefits of using CRM Content ?


I Suggest to those People Please Refer the Below amazing Articles.

So After Understanding the concept let’s Move to the other Step

How to enable CRM Content in your Organization?

Refer Below Link and Enable CRM Content in your Organization Step by Step.

What Salesforce Admin Should Know about CRM Content?

  • Publish Files to Libraries –

Go to the Libraries Tab and click on Contribute .


Choose File from your Local system and Enter Description , Select Library in which you want to Publish the file and Click on Save .



You can Share File with your Standard OR Custom Object But you need to make Lookup field of that Object with Standard Object (Content Version) of CRM Content .

  • Create a New Library –

Click on New Button and enter Name, Description and Unique Name of the Library.


  • Update Content Version –

Select any file Uploaded in CRM Content  From the Top Content Section  Or you can View file from Library and Click on Edit and Select Update Content Version and Choose file and Update the Version of that Content.

Using this you can publish a new Version of the file and update file Properties.



  • CRM Content Permissions ,Custom fields ,Customization of content Page Layouts

Search Salesforce Files in the left side Search Bar.


You would These Options After clicking on Salesforce Files


So These are the all customization which you can do regarding Library Permissions for Users, Create, modify and Delete Fields on Content Version, Manage Validation Rules etc..

Create, modify and delete custom fields is the option where you can make Standard or custom objects Lookup with Content Version So that you can upload file with the object from libraries tab.

As you see in Below Picture I can Upload File with Lead Or Account Object.


What about Developers ?


What Developer should Know about CRM content for working with Apex ?

Below is the CRM Content Object Hierarchy or you can say Data Model . This is thing which Developer must know for working with CRM Content.



ContentWorkspace – ContentWorkspace is a Library which you can use for publish File . You can use Workspace(Library) Id while making Instance of Content Version so the File publish in that Workspace.


ContentWorkspaceDoc – ContentWorkspaceDoc  Represents a link between a document and a public library in Salesforce CRM Content . It allows a document to be shared with multiple libraries.

In the ContentWorkspaceDoc there are two lookup Fields that is ContentWorkspaceId and ContentDocumentId.


ContentDocument – ContentDocument is a document that has been uploaded in library in CRM Content.

For upload file as Content Document you have to Make Instance of Content Version Because Create() call not supported in Content Document.


ContentVersion – This is a Specific Version of a Content Document(File) in CRM Content.


So these are some things Developer or Admin should Know.

Please Refer the Below Links for Complete Details of Content Object.

Click to access salesforce_content_implementation_guide.pdf

Hope you find this helpful, in case of any queries/concerns, please post a reply or drop an email to me at .