function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sukanta Anbu 7sukanta Anbu 7 

I have a lightning web component which has certain input parameters and a file upload button. I am using apex post callout to pass the parameters to save in postgress database before it gets saved in salesforce. I am facing errors in the post method

This is my LWC 
<template>
     <lightning-card title="" icon-name="custom:custom19">
        <lightning-file-upload
            label="Attach receipt"
            name="fileUploader"
            accept={acceptedFormats}
            record-id={recordId}
            onuploadfinished={handleUploadFinished}
            multiple>
    </lightning-file-upload>
    </lightning-card>
    <lightning-record-edit-form object-api-name="DMS__c" onsuccess={handleSuccess} onsubmit ={handleSubmit} >
        <div class="slds-grid">
            <div class="slds-col slds-size_1-of-2">
        <lightning-input-field field-name='Name'></lightning-input-field>
        <lightning-input-field field-name='Version__c'></lightning-input-field>
        <lightning-input-field field-name='Key_Words__c'></lightning-input-field>
        <lightning-input-field field-name='Doc_type__c'></lightning-input-field>
        <lightning-input-field field-name='Description__c'></lightning-input-field>
        </div>
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field field-name='Contract_LOB__c'></lightning-input-field>
            <lightning-input-field field-name='Active_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Competitor_Contract__c'></lightning-input-field>
            <lightning-input-field field-name='Folder__c'></lightning-input-field>
         </div>
        </div>
        <div class="slds-clearfix">
            <div class="slds-align_absolute-center">
        <lightning-button class="slds-m-top_small" type="submit" label="Upload"  onclick={showSuccessToast}></lightning-button>
        <lightning-button class="slds-m-top_small" label="Cancel" onclick={allowReset}></lightning-button>
        </div>
    </div>
    </lightning-record-edit-form>
</template>

Thefollowing is my .js file
import { LightningElement, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import POST from '@salesforce/apex/docUpload.POST';  
export default class Final extends LightningElement {
    @api recordId;
    get acceptedFormats() {
        return ['.pdf', '.png','.jpg','.jpeg'];
    }
    handleUploadFinished(event) {
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        let uploadedFileNames = '';
        for(let i = 0; i < uploadedFiles.length; i++) {
            uploadedFileNames += uploadedFiles[i].name + ', ';
        }
          var Name = component.get("v.Name");
            var Doc_type__c = component.get("v.Doc_type__c");
            var Active_Contract__c = component.get("v.Active_Contract__c");
            var Competitor_Contract__c = component.get("v.Competitor_Contract__c");
            var Version__c = component.get("v.Version__c");
            var Key_Words__c = component.get("v.Key_Words__c");
            var Folder__c = component.get("v.Folder__c");
            var action = component.get("c.POST");
            action.setParams({ file : uploadedFiles, Name : Name, Doc_type__c : Doc_type__c, Active_Contract__c : Active_Contract__c, Competitor_Contract__c : Competitor_Contract__c, Version__c : Version__c, Key_Words__c : Key_Words__c, Folder__c : Folder__c });
            action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames,
                    variant: 'success',
                }),
            );
    }
       
    handleSuccess(event) {
        console.log('onsuccess event ',event.detail.id)
        
    }
    handleSubmit(event) {
        console.log('onsubmit event Newcomp'+ event.detail.fields);
       
    }
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: 'Opearion sucessful',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    allowReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}
my apex post callout is given
public with sharing class docUpload {
    
    public String resBody {get; set;}          
        @AuraEnabled
        public static String POST(Blob file, String Name, String Doc_type__c, String Active_Contract__c, String Competitor_Contract__c, String Version__c, String Key_Words__c, String Folder__c) {
            
            Http h = new Http();
    //    String fileName = 'leads.csv';
            String url = 'https://csv-file-upload.herokuapp.com/leads/' + recordId;
            String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
            String str = file.toString();
       //     String csvBody = EncodingUtil.base64Encode(csvBlob);
            // decode 
            Blob decodedBlob = EncodingUtil.base64Decode(str);
            system.debug('string ==>'+decodedBlob);
            // convert to string
            String result = decodedBlob.toString();
            
            // assemble the body payload
            String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
            //String body = EncodingUtil.base64Encode(file) + '\n';
            String body = result + '\n';
            String footer = '--' + separationString + '--';
            String bodyPayload = header + body + footer;
            system.debug('PAYLOAD: ' + bodyPayload);
    
            HttpRequest req = new HttpRequest();
            req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
            
            req.setEndpoint(url);
            req.setMethod('POST');
            req.setBody(bodyPayload);
            system.debug('REQUEST: ' + req);
    
            // Send the request, and return a response
            HttpResponse res = h.send(req);
            System.debug(res.getBody());
            return res.getBody();
        }
}

 
Best Answer chosen by sukanta Anbu 7
David Zhu 🔥David Zhu 🔥
In method handleUploadFinished, you are using Lightning Aura component js in a LWC component.

for example: var Doc_type__c = component.get("v.Doc_type__c");
This is s typical Aura component js code.
for the above line, with LWC, you need to change the followings:

html:
<lightning-input-field field-name='Contract_LOB__c' class='Contract_LOB__c'></lightning-input-field>

in js:
var Doc_type__c = this.template.querySelector('.Doc_type__c');


Lines about calling Apex code is also a typical Aura component js.
var action = component.get("c.POST");

It should be like:
 POST({Name: Name,Doc_type__c:Doc_type__c ,......}).then(() => {

All Answers

sukanta Anbu 7sukanta Anbu 7
I am getting the following errors in apex class and in .js file
Invalid character in identifier: Key_Words__c (5:163)
Variable does not exist: recordId (9:75)
Variable does not exist: fileName (20:117)
[Line: 32, Col: 13] LWC1503: Do not use $A in LWC code.

Please let me know where i have made the error. Also the parameters and file should get saved in the endpoint url.
Please help in the above coding
David Zhu 🔥David Zhu 🔥
In method handleUploadFinished, you are using Lightning Aura component js in a LWC component.

for example: var Doc_type__c = component.get("v.Doc_type__c");
This is s typical Aura component js code.
for the above line, with LWC, you need to change the followings:

html:
<lightning-input-field field-name='Contract_LOB__c' class='Contract_LOB__c'></lightning-input-field>

in js:
var Doc_type__c = this.template.querySelector('.Doc_type__c');


Lines about calling Apex code is also a typical Aura component js.
var action = component.get("c.POST");

It should be like:
 POST({Name: Name,Doc_type__c:Doc_type__c ,......}).then(() => {
This was selected as the best answer
sukanta Anbu 7sukanta Anbu 7
@David Zhu
Hi David,
Thank you for the solution. Those errors are cleared. 
I still have the following error remaining. Unable to find Apex action class referenced as 'docUpload'.
Now my .js file is as following:
import { LightningElement, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import POST from '@salesforce/apex/docUpload.POST';  
export default class Final extends LightningElement {
    @api recordId;
    get acceptedFormats() {
        return ['.pdf', '.png','.jpg','.jpeg'];
    }
    handleUploadFinished(event) {
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        let uploadedFileNames = '';
        for(let i = 0; i < uploadedFiles.length; i++) {
            uploadedFileNames += uploadedFiles[i].name + ', ';
        }
          var Name = this.template.querySelector('.Name');
            var Doc_type__c = this.template.querySelector('.Doc_type__c');
            var Active_Contract__c = this.template.querySelector('.Active_Contract__c');
            var Competitor_Contract__c = this.template.querySelector('.Competitor_Contract__c');
            var Version__c = this.template.querySelector('.Version__c');
            var Key_Words__c = this.template.querySelector('.Key_Words__c');
            var Folder__c = this.template.querySelector('.Folder__c');
           // var action = component.get("c.POST");
            POST({Name: Name,Doc_type__c:Doc_type__c ,Active_Contract__c : Active_Contract__c, Competitor_Contract__c : Competitor_Contract__c, Version__c : Version__c, Key_Words__c : Key_Words__c, Folder__c : Folder__c });
          //  action.setParams({ file : uploadedFiles, Name : Name, Doc_type__c : Doc_type__c, Active_Contract__c : Active_Contract__c, Competitor_Contract__c : Competitor_Contract__c, Version__c : Version__c, Key_Words__c : Key_Words__c, Folder__c : Folder__c });
            action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
    
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames,
                    variant: 'success',
                }),
            );
    }
       
    handleSuccess(event) {
        console.log('onsuccess event ',event.detail.id)
        
    }
    handleSubmit(event) {
        console.log('onsubmit event Newcomp'+ event.detail.fields);
       
    }
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: 'Opearion sucessful',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    allowReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}

Also in the class the following error is still remaining.
Invalid character in identifier: Version__c (12:144)
Variable does not exist: recordId (16:75)
can you guide me for the same
David Zhu 🔥David Zhu 🔥

Are you sure you successfully saved POST method to Salesforce?
I see this line:
 String url = 'https://csv-file-upload.herokuapp.com/leads/' + recordId;

Where is variable recordID definied in class docUpload ?
I believe the missing definiation of recorID prevent POST method to be saved. Please check.

sukanta Anbu 7sukanta Anbu 7
Hi David, sorry my mistake. I forgot to update the updated apex class. This is the apex class.
public with sharing class docUpload {
    
    String Doc_type__c;
    String Active_Contract__c;
    String Competitor_Contract__c;
    String Version__c;
    String Key_Words__c;
    String Folder__c;
    String recordId;
        @AuraEnabled
        public static String POST(Blob file, String Name, String Doc_type__c, String Active_Contract__c, String Competitor_Contract__c, String Version__c, String Key_Words__c, String Folder__c) {
            
            Http h = new Http();
            String fileName;
            String url = 'https://csv-file-upload.herokuapp.com/leads/' + recordId;
            String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
            String str = file.toString();
       //     String csvBody = EncodingUtil.base64Encode(csvBlob);
            // decode 
            Blob decodedBlob = EncodingUtil.base64Decode(str);
            system.debug('string ==>'+decodedBlob);
            // convert to string
            String result = decodedBlob.toString();
            
            // assemble the body payload
            String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
            //String body = EncodingUtil.base64Encode(file) + '\n';
            String body = result + '\n';
            String footer = '--' + separationString + '--';
            String bodyPayload = header + body + footer;
            system.debug('PAYLOAD: ' + bodyPayload);
    
            HttpRequest req = new HttpRequest();
            req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
            
            req.setEndpoint(url);
            req.setMethod('POST');
            req.setBody(bodyPayload);
            system.debug('REQUEST: ' + req);
    
            // Send the request, and return a response
            HttpResponse res = h.send(req);
            System.debug(res.getBody());
            return res.getBody();
        }
}
I am still facing the issue
Variable does not exist: recordId (16:75)
Invalid character in identifier: Doc_type__c (12:66).
Can you guide me in this
sukanta Anbu 7sukanta Anbu 7
@David Zhu 🔥
The LWC component gets the above parameters as input in UI and also a upload file is aso there. If I upload the file, the file and the above given metatags should alsoo be sent via the POST callout to the URL. It should also fetch the record ID of the Account record or the opportunity record to which it has a lookup relationship ynamicaaly from the url. I have built the above code but I am not able to save the docUpload class.
Also can you guide me what changes shou be done to the code so i can upload the file and the metatags should also be passed as a single POST callout. 
David Zhu 🔥David Zhu 🔥
To pass metatags along with the file in the callout, you need to check the spec of the webservice. It depends on the format of webservice expects.

 
Praveen ChoudharyPraveen Choudhary
metatags should also be passed as a single POST callout.  
You can just check the List in this Blog :- Asktop10 (https://asktop10.com/)
hjkbm gcfgvbnhjkbm gcfgvbn
decentralized finance (DeFi (https://finscorpio.com/defi/)) offers financial instruments without relying on intermediaries such as brokerages, exchanges, and banks.  Through emerging technology, decentralized finance eliminates intermediaries and enables people, merchants, and businesses to conduct financial transactions directly.
dakava maryadakava marya
I'm really happy I was can to improve insights from this great Myeclass Login (https://tinyurl.com/3zfksnfh" target="_blank)