UPLOAD FILE FROM JAVASCRIPT REMOTING

Hi Trailblazer Community,

How many times you have got the view state exceed problem in VF Page while uploading big size images. Might be you have solved that problem by setting the blob value null after uploading image.

Today i will share the how to upload file from the Javascript Remoting. Here i am sharing the code snippet for that.


//VF Page

<apex:page controller="JsRemoting" standardStylesheets="false" sidebar="false" showHeader="false"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> function getRemoteAccount(obj_inpf) { var acc = obj_inpf.files[0]; var reader = new FileReader(); reader.readAsDataURL(acc); reader.onloadend = function(){ imgData = reader.result; Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.JsRemoting.getValue}', imgData, function(result, event){ alert(event.status) if (event.status) { alert('Response '+result); } else if (event.type === 'exception') { document.getElementById("responseErrors").innerHTML = event.message + "<br/>\n<pre>" + event.where + "</pre>"; } else { document.getElementById("responseErrors").innerHTML = event.message; } }, {escape: true} ); } } </script> <apex:form id="frm"> <apex:inputFile fileName="{!fname}" value="{!fcontent}" id="ipfile" onchange="getRemoteAccount(this)" /><br/><br/> <div id="responseErrors"></div> </apex:form> </apex:page>

//Apex Controller

global with sharing class JsRemoting { public blob fcontent{get;set;} public string fname{get;set;} public JsRemoting() {} @RemoteAction global static String getValue(String imgData) { Integer p = imgData.length(); String imag = imgData.subString(23,p); Document d = new Document(); d.name = 'test.png'; d.folderid = UserInfo.getUserId(); d.body = EncodingUtil.base64Decode(imag); insert d; if(d.id != null){ return 'Success '+d.id; } else{ return 'Fail'; } } }
What i am doing in the above code is....when i am clicking the choose file button the blob value of the image will convert in the base64 string and it will call the apex method getValue(base64 string) and i am inserting the image to the document.

Comments

Popular posts from this blog

PATH IS NOT COMING IN MOBILE??

WHATSAPP INTEGRATION WITH SALESFORCE