daily pastebin goal
20%
SHARE
TWEET

Untitled

a guest Jan 19th, 2018 45 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public void uploadToAmazonS3 () {
  2.     String filename = this.record.File_Name__c;
  3.     String attachmentBody = EncodingUtil.base64Encode(fileBlob);
  4.     String formattedDateString = DateTime.now().formatGMT('EEE, dd MMM yyyy HH:mm:ss z');
  5.     String bucketname = 'test-salesforce-upload';
  6.     String host = 's3.amazonaws.com';
  7.  
  8.     String key = credentials.key;
  9.     String secret = credentials.secret;
  10.     String stringToSign = 'PUTnnn'+formattedDateString+'nn/'+bucketname+'/'+filename;
  11.     Blob mac = Crypto.generateMac('HMACSHA1', blob.valueOf(stringToSign), blob.valueof(secret));
  12.     String signed = EncodingUtil.base64Encode(mac);
  13.     String authHeader = 'AWS' + ' ' + key + ':' + signed;
  14.  
  15.     HttpRequest req = new HttpRequest();
  16.     req.setMethod('PUT');
  17.     req.setHeader('Authorization', authHeader);
  18.     req.setEndpoint('https://s3.amazonaws.com/'+bucketname);
  19.     req.setHeader('Host', bucketname + '.' + host);
  20.     req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
  21.     req.setHeader('Content-Type', contentType);
  22.     req.setHeader('Connection', 'keep-alive');
  23.     req.setHeader('Date', formattedDateString);
  24.     req.setHeader('ACL', 'public-read-write');
  25.     Blob blobBody = EncodingUtil.base64Decode(attachmentBody);
  26.     req.setBodyAsBlob(blobBody);
  27.  
  28.     Http http = new Http();
  29.     HTTPResponse resp = http.send(req);
  30.     System.debug(resp);
  31. }
  32.    
  33. DEBUG|System.HttpResponse[Status=Forbidden, StatusCode=403]
RAW Paste Data
Top