0

Still faxing the same issue.After adding two URL's.

<apex:page showHeader="false" sidebar="false" lightningStyleSheets="true" standardStylesheets="false" controller="TW_MultipleUploadCtrl">    

    <html>  
        <head>  
            <apex:slds /> 
           <apex:pageMessages />
            <apex:includeScript value="https://code.jquery.com/jquery-3.3.1.js"/> 
            <script>
            var upload;
             var uploadedDocuments;
            function loadUploadedDocuments(){
                 upload = document.getElementById('upload');
                 uploadedDocuments = document.getElementById("contentDocuments");
                upload.style.display = 'none';
                uploadedDocuments.style.display = 'block';
                //event.preventDefault();
            }
            function loadUploadDocuments(){
                upload.style.display = 'block';
                uploadedDocuments.style.display = 'none';

            }
            function OpenFile(){ 
                var uploadedFiles = document.getElementById('addr');
                var uploadButton;
                //alert(document.getElementById('addr').files[0].type);
                if(uploadedFiles.files.length > 0){
                    $('[id*=uploadBtn]').attr('style','display:block');
                    //uploadButton = document.getElementById("{!$Component.uploadBtn}");
                    // uploadButton.style.display = 'block';
                }
            }
            function deleteFiles(documentID){
                if(confirm("Are you Sure to Delete this File?")){
                    Visualforce.remoting.Manager.invokeAction(
                        '{!$RemoteAction.TW_MultipleUploadCtrl.deleteFilesMethod}',
                        documentID,
                        function(result, event) {
                            if(result == 'deleteSuccess'){
                                alert('File Deleted Successfully');
                            }
                            else{
                                alert('Deletion Error!');
                            }
                            if(event.type === 'exception') {
                                console.log("Exception occured");  
                            } else if(event.status) { 
                                console.log(result);  
                            }
                            $("#contentDocuments").load(" #contentDocuments > *");
                        });
                }
            }
            function openDOCModal(docId){
                var p  = '<embed src="/_swf/190003/sfc/flex/DocViewer.swf" flashvars="shepherd_prefix=/sfc/servlet.shepherd&v='+docId+'&mode=chatter_bubble&in_tests=false" width="100%" height="100%" align="middle" id="renditionLarge" quality="high" bgcolor="#f3f3f3" name="renditionLarge" allowscriptaccess="always" allowfullscreen="true" pluginspage="http://www.adobe.com/go/getflashplayer" wmode="opaque" type="application/x-shockwave-flash">'
                $("#previewDOCModal").addClass('slds-fade-in-open');
                $("#previre").addClass('slds-backdrop_open');
                $("#previewDOCBodyHTML").html(p);
            }
            function closeDOCModal(){
                $("#previre").removeClass('slds-backdrop_open');
                $("#previewDOCModal").removeClass('slds-fade-in-open'); 
            }
            function showAppCoapp(){
                //document.getElementById('uploadedTable').style.display = 'block';
                callDocuments();
                //$("#uploadedTable").load("#uploadedTable > *");
            }
            function showTable(){
                document.getElementById('uploadedTable').style.display = 'block';
            }

            //function starts  
            $(function(){  
                var fileLenght=0;
                var checkFiles = true;
                var FileUploading = 0;  
                var FileUploaded = 0;
                $('#uploadFileBtn').click(function(){
                    $("#addr").click();
                });
                $('#uploadBtn').click(function() {
                    var v=document.getElementById('addr');  
                    console.log(v.files.length);  
                    fileLenght = v.files.length;
                    for (var i = 0; i < v.files.length; i++) {  
                        uploadSelectedFile(v.files[i], function(err, res){   
                            FileUploading += 1;  
                            if (FileUploading === FileUploaded){
                                if(checkFiles){
                                    alert('Upload Successful');
                                    checkFiles = false; 
                                }
                                /*else{
                                    alert('Error,file upload failed.Please contact system administrator');
                                }*/
                                //blank input file value   
                                document.getElementById("addr").value = "";     
                            }
                        })  
                    }

                });  

                // var FileUploading = 0;  
                // var FileUploaded = 0;  
                var ids;  
                var uploadSelectedFile = function(file, callback) {  
                    filetoBase64(file, function(err, content){  
                        var conVer_object = {  
                            ContentLocation : 'S',  
                            VersionData : content,   
                            PathOnClient : file.name,   
                            Title : file.name   
                        };  
                        $.ajax({  
                            url: '/services/data/v45.0/sobjects/ContentVersion',  
                            data: JSON.stringify(conVer_object ),  
                            type: 'POST',  
                            processData: false,  
                            contentType: false,  
                            headers: {'Authorization': 'Bearer {!$Api.Session_ID}', 'Content-Type': 'application/json'},  
                            xhr: function(){  
                                var xhr = new window.XMLHttpRequest();  
                                //Upload progress  
                                xhr.upload.addEventListener("progress", function(evt){  
                                    if (evt.lengthComputable) {  
                                        $('#progress_bar_container').css('display', 'block');  
                                        var percentComplete = evt.loaded / evt.total;  
                                        console.log('percentComplete '+percentComplete );  
                                        var percentCompletex= percentComplete*100;  
                                        $('#percentText').html("Uploading. Please wait... "+Math.round(percentCompletex)+"%");  
                                        $('.progress').css('width', percentCompletex+ "%");  
                                        if(percentCompletex == 100){  
                                            $('#progress_bar_container').css('display', 'none');  
                                        }  
                                    }  
                                }, false);  
                                return xhr;  
                            },  
                            success: function(response) {  
                                FileUploaded += 1;  
                                console.log(response.id); // the id of the attachment  
                                //ids.push(response.id);
                                ids = response.id;
                                uploadToOpportunity(ids);    
                                console.log('Ids: ' +ids);  
                                //$('#records').html('File has been uploaded. Uploaded File ids: ' +ids);   
                                if(fileLenght == FileUploaded ){   
                                    //calculateLocation(ids.toString());  
                                }  
                                callback(null, true)  
                            },  
                        });  
                    });  
                }  
                //Read file  
                var filetoBase64 = function(file, callback){  
                    var reader = new FileReader();  
                    reader.onload = function() {  
                        var myFileContents = reader.result;  
                        var base64Mark = 'base64,';  
                        var dataStart = myFileContents.indexOf(base64Mark) + base64Mark.length;  
                        myFileContents = myFileContents.substring(dataStart);  
                        callback(null, myFileContents);  
                    }  
                    reader.readAsDataURL(file);  
                }  
                });  
            </script>  
            <style>
                .header{
                background:#ea0c20;padding-right:0.25rem;padding-left:0px;border-radius:0.3rem;
                }
                .commandLink{
                text-decoration:none;
                color:#fff;
                margin: 0px;
                display: inline-block;
                letter-spacing: 0.15rem;
                text-transform: uppercase;
                font-size:1rem;
                font-stretch:wider;
                font-family: Arial,Helvetica,sans-serif; 
                font-weight:bold;    
                display: flex;
                justify-content: center;
                align-content: center;
                align-items: center;
                margin: auto;
                }
                .slds-scope .slds-page-header{  
                border-radius: 0px;  
                box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);  
                }
                .bodyPart{  
                padding:10px;  
                } 
                a:hover,a:focus{
                text-decoration: none;
                outline: none;
                }
                .tab .nav-tabs{
                border: none;
                border-bottom: 2px solid #079fc9;
                margin: 0;
                }
                .tab .nav-tabs li a{
                padding: 10px 20px;
                margin: 0 10px -1px 0;
                font-size: 17px;
                font-weight: 600;
                color: #293241;
                text-transform: uppercase;
                border: 2px solid #e6e5e1;
                border-bottom: none;
                border-radius: 5px 5px 0 0;
                z-index: 1;
                position: relative;
                transition: all 0.3s ease 0s;
                }
                .tab .nav-tabs li a:hover,
                .tab .nav-tabs li.active a{
                background: #fff;
                color: #079fc9;
                border: 2px solid #079fc9;
                border-bottom-color: transparent;
                }
                .tab .nav-tabs li a:before{
                content: "";
                display: block;
                height: 2px;
                background: #fff;
                position: absolute;
                bottom: -2px;
                left: 0;
                right: 0;
                transform: scaleX(0);
                transition: all 0.3s ease-in-out 0s;
                }
                .tab .nav-tabs li.active a:before,
                .tab .nav-tabs li a:hover:before{ transform: scaleX(1); }
                .tab .tab-content{
                padding: 10px;
                font-size: 17px;
                color: #6f6f6f;
                line-height: 30px;
                letter-spacing: 1px;
                position: relative;
                }
                @media only screen and (max-width: 479px){
                .tab .nav-tabs{ border: none; }
                .tab .nav-tabs li{
                width: 100%;
                text-align: center;
                margin-bottom: 15px;
                }
                .tab .nav-tabs li a{
                margin: 0;
                border-bottom: 2px solid transparent;
                }
                .tab .nav-tabs li a:before{
                content: "";
                width: 100%;
                height: 2px;
                background: #079fc9;
                position: absolute;
                bottom: -2px;
                left: 0;
                }
                }
            </style>  
        </head> 
        <!--Spinner loading-->
        <apex:actionStatus id="status">
            <apex:facet name="start">
                <div class="slds-spinner_container" style="position: fixed;">
                    <div role="status" class="slds-spinner slds-spinner--large slds-spinner--brand">
                        <div class="slds-spinner__dot-a"></div>
                        <div class="slds-spinner__dot-b"></div>
                    </div>
                </div>
            </apex:facet>
        </apex:actionStatus>
        <!--Spinner loading end-->
        <body>  
            <apex:form id="f">
                <div class="slds-scope" id="upload" style="border:1px solid #D9D9D9;">
                    <apex:panelGrid columns="3" id="Grid" border="2" cellpadding="500px" styleClass="header">
                        <apex:commandLink onclick="loadUploadDocuments();return false;" status="status" title="UPLOAD" value="UPLOAD" styleClass="commandLink" style="text-decoration: none;color: #fff;">    
                        </apex:commandLink>
                        <apex:commandLink title="UPLOADED DOCUMENTS" value="UPLOADED DOCUMENTS" style="text-decoration:none;color: #fff;"
                                      styleClass="commandLink" status="status" onclick="loadUploadedDocuments();return false;"/>   

                    </apex:panelGrid>
                    <div style="float:left;margin-left:1%;margin-top:1%;"> 
                        <label id="documentType" class="slds-text-title_caps">Select Customer</label>
                        <apex:selectList title="Select Applicant Name" size="1" styleClass="slds-select" style="width:130%;"
                                         value="{!selectedCustomer}"><br/>
                            <apex:selectOptions value="{!customers}"></apex:selectOptions>
                        </apex:selectList>
                    </div>
                    <div style="float:left;margin-left:5%; margin-top:1%;"> 
                        <label id="documentType" class="slds-text-title_caps">Document Type</label>
                        <apex:selectList title="Document Type" size="1" styleClass="slds-select" style="width:130%;" value="{!selectedDoc}"><br/>
                            <apex:selectOptions value="{!documents}"></apex:selectOptions>
                        </apex:selectList>
                    </div><br/><br/><br/><br/> 

                    <div id="progress_bar_container" style="display:none; padding:10px;">  
                        <span id="percentText"></span>  
                        <div class="slds-progress-bar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="25" role="progressbar">  
                            <span class="slds-progress-bar__value progress" style=" width: 0%;">  
                                <span class="slds-assistive-text">Progress: 25%</span>  
                            </span>  
                        </div>  
                    </div><br/> 
                    <apex:actionFunction action="{!uploadDocuments}" name="uploadToOpportunity" reRender="f" status="status">
                        <apex:param assignTo="{!contenVerId}" name="contenVersionId" value=""/>
                    </apex:actionFunction>
                    <div class="slds" style="border:1px solid #D9D9D9;"> 
                        <div class="bodyPart">  
                            <input type="file" name="files[]" multiple="multiple" id="addr" onChange = "OpenFile()" 
                                   accept="image/*,.pdf" style=""/> <br/> <br/><br/> <br/>
                            <!--<input type="button" id="uploadFileBtn" name="Upload Files" value="Upload Files" class="slds-button slds-button--brand"/><br/> <br/><br/> <br/>-->
                            <input type="button" id="uploadBtn" name="Address" value="Upload" class="slds-button slds-button--brand" style="display:none"/>
                        </div>  
                        <div id="uploadedrec">  
                            <span id="records" style=" color:green; ">  
                            </span>  
                        </div>  
                    </div> 
                </div>


                <!--Uploaded documents div-->                        
                <div class="slds-scope" id="contentDocuments" style="border:1px solid #D9D9D9;display:none">  
                    <apex:panelGrid columns="3" id="Grid2" border="2" cellpadding="500px" styleClass="header">
                        <apex:commandLink onclick="loadUploadDocuments();return false;" title="UPLOAD" value="UPLOAD" styleClass="commandLink" style="text-decoration: none;color: #fff;">    
                        </apex:commandLink>
                        <apex:commandLink title="UPLOADED DOCUMENTS" value="UPLOADED DOCUMENTS" style="text-decoration:none;color: #fff;"
                                      styleClass="commandLink" status="status" onclick="loadUploadedDocuments();return false;"/>   

                    </apex:panelGrid>
                    <div style="float:left;margin-left:1%;margin-top:1%;"> 
                        <label id="documentType" class="slds-text-title_caps">Select Customer</label>
                        <apex:selectList title="Select Applicant Name" size="1" styleClass="slds-select" style="width:130%;"
                                         onchange="showAppCoapp();"   value="{!selectedCustomerUploaded}" ><br/>
                            <apex:actionFunction action="{!displayDocs}" name="callDocuments" reRender="uploadedTable" status="status"/>
                            <apex:selectOptions value="{!customers}">
                            </apex:selectOptions>
                        </apex:selectList><br/><br/>
                    </div>

                    <apex:outputPanel id="uploadedTable">
                        <apex:pageBlock title=""> 
                            <apex:pageBlockTable id="table" styleClass="slds-table slds-table_cell-buffer slds-table_bordered" value="{!showDocuments}"
                                                 var="Sd">
                                <apex:column value="{!Sd.Title}" headerValue="DOCUMENT NAME" />
                                <apex:column value="{!Sd.File_Type__c}" headerValue="DOCUMENT TYPE"/> 
                                <apex:column value="{!Sd.CreatedDate}" headerValue="CREATED DATE"/>  
                                <apex:column headerValue="PREVIEW">
                                    <a href="#" onClick="openDOCModal('{!Sd.Id}'); return false;" style="text-decoration:none;">PREVIEW</a>    
                                </apex:column>
                                <apex:column headerValue="DOWNLOAD">
                                    <apex:outputLink value="/sfc/servlet.shepherd/version/download/{!Sd.Id}?asPdf=false&operationContext=CHATTER" style="text-decoration:none;">
                                        <apex:outputText value="DOWNLOAD" />
                                    </apex:outputLink>
                                </apex:column>
                                <apex:column headerValue="DELETE">
                                    <a href="" id="deleteFiles" onclick="javascript:deleteFiles('{!Sd.Id}')" style="text-decoration:none;">DELETE</a>
                                </apex:column>
                            </apex:pageBlockTable>
                        </apex:pageBlock>
                    </apex:outputPanel>
                    <div id="uploadedrec">  
                        <span id="records" style=" color:green; ">  
                        </span>  
                    </div>  
                </div>
                <div class="slds-backdrop" id="previre"></div>
                <div class="slds-modal" role="dialog" id="previewDOCModal" >
                    <div class="slds-modal__container slds-modal__container--center" style="width:auto;max-width:50rem;">
                        <div class="slds-modal__header">
                            <h2 class="slds-text-heading--medium">Uploaded Document(s)</h2>
                            <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick="closeDOCModal();return false;">
                                <span class="slds-input__icon" aria-hidden="true">
                                    <img src="{!URLFOR($Resource.SLDS222, '/assets/icons/utility/close_60.png')}" />
                                </span>
                                <span class="slds-assistive-text">Close</span>
                            </button>
                        </div>
                        <div class="slds-modal__content " id="previewDOCBodyHTML" style="height: 30rem;">   

                        </div>            
                        <!--<div class="slds-modal__footer">
<button class="slds-button slds-button--neutral slds-button--brand" onClick="prevAF();return false" >Previous</button>
<button class="slds-button slds-button--neutral slds-button--brand" onClick="nxtAF();return false" >Next</button>
</div>-->
                    </div>
                </div>
            </apex:form>  
        </body>  
    </html>  
</apex:page>

//Controller
global class TW_MultipleUploadCtrl {
    Public List<String> getFileType {get;set;}
    Public  List<String> getTitle {get;set;}
    Public  List<String> getTextPreview {get;set;}
    Public  List<String> getVersionData {get;set;}
    Public static String imagesUrl {get;set;}
    Public Id contentVersionId {get;set;}
    Public String contenVerId{get;set;}
    Public String selectedDoc{get;set;}
    Public List<selectOption> documents {get;set;}
    Public List<selectOption> customers {get;set;}
    Public  String selectedCustomer{get;set;}
    Public  String selectedCustomerUploaded{get;set;}
    Public Id opportunityId{get; set;}


    Public TW_MultipleUploadCtrl(){
        try{
        opportunityId = apexpages.currentpage().getparameters().get('id'); 
        system.debug('opportunityId '+opportunityId);
        selectedCustomerUploaded = 'Applicant';
        //Id opportunityId = '0069D000001rkq6QAA';
        documents = new List<selectOption>();   
        Schema.DescribeFieldResult fieldResult = ContentVersion.File_Type__c.getDescribe();   
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

        for( Schema.PicklistEntry f : ple)
        {
            documents.add(new SelectOption(f.getLabel(), f.getValue()));
        } 
        customers = new List<selectOption>();
        system.debug('opportunityId '+opportunityId);
        String coapplicantType =  [SELECT CoApplicant_Type__c FROM Opportunity where id =: opportunityId][0].CoApplicant_Type__c;
        //customers.add(new selectOption('--None--','--None--'));  
        customers.add(new selectOption('Applicant','Applicant'));
        customers.add(new selectOption(coapplicantType,coapplicantType));

    }

    catch(Exception ex){ 
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Some error occured. Please contact Administrator.'));
            system.debug('Exception at Line '+ex.getLineNumber()+' '+ex);
        }
    }
    //return  documents;     

Removed some methods due to body size limit..Code is working fine but not able to upload files(2nd time),after uploading once if i am trying to upload anything again the upload button is not getting called.Thought this could be something with CORS origin error so was trying to fix that.

1

You need to whitelist your own visualforce page with the request you're trying to perform.

Try going to Setup -> CORS and add https://*.visual.force.com as a whitelisted origin

| improve this answer | |
  • Added the same in Whitelisted Origin but still receiving the same error. – Deepak Agarwal Apr 16 '19 at 10:14
  • @DeepakAgarwal Also add https://*.my.salesforce.com as well, and if you're using Lightning, https://*.lightning.force.com – Brian Miller Apr 16 '19 at 13:17
  • Hi Brian thanks for the response. Issue still exists please see my updated post. – Deepak Agarwal Apr 17 '19 at 6:13
  • I'm not sure - if you can show some code of what you're trying to accomplish and some more context, that would be helpful – Brian Miller Apr 17 '19 at 14:27
  • In my context i have written a vf page for uploading multiple files at once. When i am uploading the file immediately after upload its giving me the error even though upload is success. Providing the code for reference. – Deepak Agarwal Apr 18 '19 at 6:20
1

Cross-Origin Resource Sharing (CORS) enables web browsers to request resources from origins other than their own (cross-origin). For example, using CORS, JavaScript code at https://www.example.com could request a resource from https://www.salesforce.com. To access supported Salesforce APIs, Apex REST resources, and Lightning Out from JavaScript code in a web browser, add the origin serving the code to a Salesforce CORS whitelist.

In Salesforce, add the origin serving the code to a CORS whitelist. If a browser that supports CORS makes a request to an origin in the whitelist, Salesforce returns the origin in the Access-Control-Allow-Origin HTTP header, along with any additional CORS HTTP headers. If the origin is not included in the whitelist, Salesforce returns HTTP status code 403.

  1. From Setup, enter CORS in the Quick Find box, then select CORS.
  2. Select New.
  3. Enter an origin URL pattern.

The origin URL pattern must include the HTTPS protocol (unless you’re using your localhost) and a domain name and can include a port. The wildcard character (*) is supported and must be in front of a second-level domain name. For example, https://*.force.com adds all subdomains of force.com to the whitelist.

The origin URL pattern can be an IP address. However, an IP address and a domain that resolve to the same address are not the same origin, and you must add them to the CORS whitelist as separate entries.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.