[Salesforce]ApexでawsへファイルUpload

ApexでawsへファイルUpload

    public Integer fileUpload(Attachment file){

        String attachmentBodyEncoded = EncodingUtil.base64Encode(file.Body);
        String formattedDateString = Datetime.now().formatGMT('EEE, dd MMM yyyy HH:mm:ss z');
        String key = awsAccessKey;
        String secret = awsSecretAccessKey;
        String bucketname = awsBucket;
        String host = awsService + '-' + awsReign + '.amazonaws.com'; 
        String method = 'PUT';
        String fileNameEncoded	= EncodingUtil.urlEncode(file.Name, 'UTF-8');

        HttpRequest req = new HttpRequest();
        req.setMethod(method);
        req.setEndpoint('https://' + bucketname + '.' + host + '/' + bucketname + '/' + fileNameEncoded);
        req.setHeader('Host', bucketname + '.' + host);
        req.setHeader('Content-Length', String.valueOf(attachmentBodyEncoded.length()));
        req.setHeader('Content-Encoding', 'UTF-8');
        req.setHeader('Content-type', file.ContentType);
        req.setHeader('Connection', 'keep-alive');
        req.setHeader('Date', formattedDateString);
        req.setHeader('ACL', 'public-read-write');
        req.setBodyAsBlob(EncodingUtil.base64Decode(attachmentBodyEncoded));
         
        String stringToSign = 'PUT\n\n' +
        file.ContentType + '\n' +
        formattedDateString + '\n' +
        '/' + bucketname + '/' + bucketname + '/' + fileNameEncoded;
         
        Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof(secret));
        String signed = EncodingUtil.base64Encode(mac);
        String authHeader = 'AWS' + ' ' + key + ':' + signed;
        req.setHeader('Authorization',authHeader);
         
        Http http = new Http();
        HTTPResponse res = http.send(req);

        return res.getStatusCode();

    }

投稿者: kinkun

保有資格 Salesforce Certified Platform App Builder T Salesforce Certified Platform Developer I Salesforce Certified Platform Developer II Salesforce Certified Administrator

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です