VenkateswaraT
3/14/2017 - 2:17 AM

Java Script Site Upload Image Code (Salesforce)

Java Script Site Upload Image Code (Salesforce)

<apex:page tabStyle="Account"  showHeader="true" controller="GetSessionId"  action="{!getAccessToken}" >
    <apex:form id="formId">
            <script src="/soap/ajax/32.0/connection.js" type="text/javascript"></script>
            <script src="/soap/ajax/32.0/apex.js" type="text/javascript"></script>
            <script type="text/javascript">
                var __sfdcSessionId = '{!AccessToken}';
            </script>
            <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
            <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
            <script src="../../soap/ajax/29.0/connection.js"></script>
            
            <script type="text/javascript">
                        function uploadFile(parentId) {
                         $j = jQuery.noConflict();
                        $j("input[type=file]").each(function() {
                            filesToUpload=[];
                            filesToUpload.push($j(this)[0].files[0]);
                        });
                        for (var i = 0, f; f = filesToUpload[i]; i++) {
                            var reader = new FileReader();
                            reader.file = f;
                            reader.onload = function(e) {
                                var att = new sforce.SObject("Attachment");
                                
                                att.Name = this.file.name;
                                att.ContentType = this.file.type;
                                
                                
                                att.ParentId = parentId;
                                var binary = "";
                                var bytes = new Uint8Array(e.target.result);
                                var length = bytes.byteLength;
                                for (var i = 0; i < length; i++) {
                                    binary += String.fromCharCode(bytes[i]);
                                }
                                att.Body = (new sforce.Base64Binary(binary)).toString();
                                sforce.connection.create([att], {
                                    onSuccess: function(result, source) {
                                        if (result[0].getBoolean("success")) {                              
                                            saveImage();
                                            alert('Your image was successfully loaded.');
                                            return true;
                                        } else {
                                            return false;
                                            console.log("failed to create attachment " + result[0]);
                                        }
                                    },
                                    onFailure: function(error, source) {
                                        console.log("an error has occurred " + error);
                                    }
                                });
                            };
                            reader.readAsArrayBuffer(f);
                        }
                    }
                </script>
                <apex:pageBlock >
                    <apex:actionFunction name="saveImage" action="{!logOut}" rerender="formId"/>
                <apex:pageblocksection title="Layout Install Sketch" columns="2" collapsible="false" >
                        <apex:pageblocksectionItem >
                                <input type="file" class="fileInput"  style="width:180px" /> 
                        </apex:pageblocksectionItem>
                        <apex:commandButton value="Upload" onclick="uploadFile('0039000001GzyIZ'); return false" style="width:16;height:16;" /> 
                </apex:pageblocksection>
                    </apex:pageBlock>
        <br/>
        <br/>
        <br/>
        LogOut Status==>{!Logout_Status}
            </apex:form>   
            <style>
       
 #upload,.fileInput { 
                               color: #333;
                        margin: 1px;
                        padding: 2px 3px;
                        border-width: 1px;
                        border-style: solid;
                        border-color: #B5B5B5 #B5B5B5 #7F7F7F;
                        -moz-border-top-colors: none;
                        -moz-border-right-colors: none;
                        -moz-border-bottom-colors: none;
                        -moz-border-left-colors: none;
                        border-image: none;
                        
                        font-weight: bold;
                        font-size: 0.9em;
                        border-radius: 3px;
                               
       }
    </style>
</apex:page>
                         
public class GetSessionId {
    public String accessToken{get;set;}
    public String token_type{get;set;}
    public String logout_Status{get;set;}
  public void getAccessToken(){
        HttpRequest req=new HttpRequest();
        req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
        req.setMethod('POST');
        String Body;
        Body='grant_type=password&';
        Body+='client_id=3MVG9Y6d_Btp4xp46_fNFBncz2_KZ8eKzw4gs.._oCz2GP_aVxGSVZToiPUlh4HgKHFByfKmez.pPtssMdOTb&';
        Body+='client_secret=3283816375580744284&';
        body+='username=VenkateswaraTholla@hotmail.com&';
        Body+='password=harekrishna!1ABnkDvsZc5SzdkGV0AEjN5fjFI5';
        req.setBody(Body);
        Http p=new Http();
        HttpResponse res=new HttpResponse();
        res=p.send(req);
        GetSessionId.JSON2Apex parser_Obj=new GetSessionId.JSON2Apex();
            AccessToken=parser_Obj.parse(res.getBody()).access_token;
          Token_type=parser_Obj.parse(res.getBody()).Token_type;
    }
    public class JSON2Apex {
    public String access_token;
    public String instance_url;
    public String id;
    public String token_type;
    public String issued_at;
    public String signature;
    public  JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
}
    public void logOut(){
        HttpRequest req=new HttpRequest();
        req.setEndpoint('https://login.salesforce.com/services/oauth2/revoke?token='+AccessToken);
        req.setMethod('POST');
        req.setHeader('Content-Type','application/x-www-form-urlencoded');
        req.setBody('token=' + Token_type);
        
        Http http = new Http();
        HTTPResponse resp = http.send(req);
        Logout_Status=resp.getBody();
        System.debug(Logout_Status);
    }
}