首页 > 解决方案 > 文件从 Salesforce LWC 上传到 Amazon S3(无顶点)

问题描述

我尝试创建一个 LWC 组件,该组件的工作是在 Amazom S3 存储桶中上传文件。我已经完美地配置了 AWS 存储桶,测试它通过邮递员上传文件。但我无法从 LWC 组件归档。我收到了这个错误。在此处输入图像描述

我正在关注本教程

我在下面的 salesforce.Images 中 配置了CSP 可信站点CORS :CSP 可信站点 在此处输入图像描述

这是我的代码:

import { LightningElement, track, wire } from "lwc";
import { getRecord } from "lightning/uiRecordApi";
import { loadScript } from "lightning/platformResourceLoader";
import AWS_SDK from "@salesforce/resourceUrl/awsjssdk";
import getAWSCredential from '@salesforce/apex/CRM_AWSUtility.getAWSCredential';

export default class FileUploadComponentLWC extends LightningElement {
    /*========= Start - variable declaration =========*/
    s3; //store AWS S3 object
    isAwsSdkInitialized = false; //flag to check if AWS SDK initialized
    @track awsSettngRecordId; //store record id of custom metadata type where AWS configurations are stored
    selectedFilesToUpload; //store selected file
    @track showSpinner = false; //used for when to show spinner
    @track fileName; //to display the selected file name

    /*========= End - variable declaration =========*/

    //Called after every render of the component. This lifecycle hook is specific to Lightning Web Components,
    //it isn’t from the HTML custom elements specification.
    renderedCallback() {
        if (this.isAwsSdkInitialized) {
            return;
        }
        Promise.all([loadScript(this, AWS_SDK)])
            .then(() => {
                //For demo, hard coded the Record Id. It can dynamically be passed the record id based upon use cases
             //   this.awsSettngRecordId = "m012v000000FMQJ";
            })
            .catch(error => {
                console.error("error -> " + error);
            });
    }

    //Using wire service getting AWS configuration from Custom Metadata type based upon record id passed

    @wire(getAWSCredential)
    awsConfigData({ error, data }) {
        if (data) {
            console.log('data: ',data)
            let awsS3MetadataConf = {};
            let currentData = data[0]
            //console.log("AWS Conf ====> " + JSON.stringify(currentData));
            awsS3MetadataConf = {
                s3bucketName: currentData.Bucket_Name__c,
                awsAccessKeyId: currentData.Access_Key__c,
                awsSecretAccessKey: currentData.Secret_Key__c,
                s3RegionName: 'us-east-1'
            };
            this.initializeAwsSdk(awsS3MetadataConf); //Initializing AWS SDK based upon configuration data
        } else if (error) {
            console.error("error ====> " + JSON.stringify(error));
        }
    }

    //Initializing AWS SDK
    initializeAwsSdk(confData) {
        const AWS = window.AWS;
        AWS.config.update({
            accessKeyId: confData.awsAccessKeyId, //Assigning access key id
            secretAccessKey: confData.awsSecretAccessKey //Assigning secret access key
        });

        AWS.config.region = confData.s3RegionName; //Assigning region of S3 bucket

        this.s3 = new AWS.S3({
            apiVersion: "2006-03-01",
            params: {
                Bucket: confData.s3bucketName //Assigning S3 bucket name
            }
        });
        console.log('S3: ',this.s3)
        this.isAwsSdkInitialized = true;
    }

    //get the file name from user's selection
    handleSelectedFiles(event) {
        if (event.target.files.length > 0) {
            this.selectedFilesToUpload = event.target.files[0];
            this.fileName = event.target.files[0].name;
            console.log("fileName ====> " + this.fileName);
        }
    }

    //file upload to AWS S3 bucket
    uploadToAWS() {
        if (this.selectedFilesToUpload) {
            console.log('uploadToAWS...')
            this.showSpinner = true;
            let objKey = this.selectedFilesToUpload.name
                .replace(/\s+/g, "_") //each space character is being replaced with _
                .toLowerCase();

            console.log('objKey: ',objKey);
            //starting file upload
            this.s3.putObject(
                {
                    Key: objKey,
                    ContentType: this.selectedFilesToUpload.type,
                    Body: this.selectedFilesToUpload,
                    ACL: "public-read"
                },
                err => {
                    if (err) {
                        this.showSpinner = false;
                        console.error(err);
                    } else {
                        this.showSpinner = false;
                        console.log("Success");
                        this.listS3Objects();
                    }
                }
            );
        }
        this.showSpinner = false;
        console.log('uploadToAWS Finish...')
    }

    //listing all stored documents from S3 bucket
    listS3Objects() {
        console.log("AWS -> " + JSON.stringify(this.s3));
        this.s3.listObjects((err, data) => {
            if (err) {
                console.log("Error listS3Objects", err);
            } else {
                console.log("Success listS3Objects", data);
            }
        });
    }
}

请帮助某人。谢谢你提前。

标签: amazon-web-servicesamazon-s3salesforcesalesforce-lightninglwc

解决方案


问题解决了。我们在 AWS 配置中发现了问题。


推荐阅读