Newer Version Available
Upload File Content to Amazon S3
Use the code snippet below to create an LWC component to upload the file and add it to a
Lightning page.
Here, uploadParams is the output from the getS3UploadUrl function in the ConnectApiHelper Apex class. The LWC uses the URLs from the response of Initialize Upload to upload the files to the Amazon S3 bucket.
Single-Part Upload
1export default class SinglePartUploader {
2async upload() {
3const uploadUrl = this.uploadParams.fileUploadUrl.replaceAll('&', '&');
4const response = await fetch(uploadUrl, {
5method: 'PUT',
6body: this.file,
7headers: {
8'Content-Type': this.file.type
9}
10});
11
12if (response.status !== 200) {
13// Handle the error
14}
15
16// The upload completion process will be discussed in the next step
17this.onComplete();
18}
19}Multi-Part Upload
For large files, the LWC splits the file into chunks of 100 MB and uploads them.
1export default class MultiPartUploader {
2async upload() {
3const promises = this.uploadParams.contentHubUploadUrlRepresentations
4.map(uploadUrlRep => this.uploadFileInParts(uploadUrlRep));
5await Promise.all(promises);
6// The upload completion process will be discussed in the next step
7this.onComplete(this.uploadParts);
8}
9
10uploadFileInParts(uploadUrlRep) {
11// Get the chunk for the part
12const start = (uploadUrlRep.partNumber - 1) * this.uploadParams.partSize;
13const end = Math.min(start + this.uploadParams.partSize, this.file.size);
14const chunk = this.file.slice(start, end);
15
16// Upload the chunk using fetch
17const uploadUrl = uploadUrlRep.partUrl.replaceAll('&', '&');
18const response = await fetch(uploadUrl, {
19method: 'PUT',
20body: chunk,
21headers: {
22'Content-Type': this.file.type
23}
24});
25
26if (response.status === 200) {
27// The upload completion process will be discussed in the next step
28this.uploadParts.push({
29partNumber: uploadUrlRep.partNumber,
30eTag: response.headers.get('ETag'),
31});
32}
33else{
34//Handle the error here
35reject();
36}
37
38resolve();
39}
40}