How to Upload an Attachment to Salesforce Using LWC (Lightning Web Component) and Multipart Form Data
Here's an example of an LWC (Lightning Web Component) code snippet that demonstrates how to upload an attachment using multipart form data and a boundary:
<template>
<lightning-card title="Upload Attachment">
<lightning-input type="file" label="Select File" accept=".txt,.pdf,.docx" onchange={handleFileChange}></lightning-input>
<lightning-button label="Upload" variant="brand" onclick={handleUpload}></lightning-button>
</lightning-card>
</template>
import { LightningElement, track } from 'lwc';
export default class UploadAttachment extends LightningElement {
@track file;
handleFileChange(event) {
this.file = event.target.files[0];
}
handleUpload() {
if (this.file) {
const boundary = '----WebKitFormBoundary' + new Date().getTime();
const formData = new FormData();
formData.append('file', this.file, this.file.name);
const request = new XMLHttpRequest();
request.open('POST', '/uploadEndpoint');
request.setRequestHeader('Content-Type', `multipart/form-data; boundary=${boundary}`);
request.send(formData);
}
}
}
In this example, the LWC component consists of a lightning-card containing a file input field and an upload button. The handleFileChange function is triggered when a file is selected, and it assigns the selected file to the file property.
The handleUpload function is called when the upload button is clicked. It first checks if a file has been selected. If a file exists, a new FormData object is created and the file is appended to it using the append method. The file name is also specified in the append method.
Next, an XMLHttpRequest object is created, and the open method is called to specify the HTTP method ('POST') and the endpoint ('/uploadEndpoint') to which the file will be uploaded. The setRequestHeader method is used to set the 'Content-Type' header to multipart/form-data and includes the boundary value.
Finally, the send method is called on the XMLHttpRequest object, passing in the formData object. This initiates the file upload.
Note that in this example, the actual endpoint for uploading the file is represented by /uploadEndpoint. You would need to replace it with the appropriate endpoint in your application.
I hope this example helps you understand how to upload an attachment using multipart form data and a boundary in an LWC component!