从Apex上载CSV文件到s3

时间:2018-02-20 17:58:27

标签: amazon-web-services authentication amazon-s3 apex

我需要将Apex中的CSV文件上传到s3中的全局存储桶并保留URL。

下面介绍的是使用AWS请求签名过程的相同方法。

 public static void uploadCSVFileToS3(String csvFile, String filename, String awsAccessKey, String awsSecretKey, String bucketname){
    try{
        String formattedDateString = Datetime.now().format('EEE, dd MMM yyyy HH:mm:ss');
        String requestType = 'PUT';
        String contentType = 'text/csv';
        String filePath = 'https://s3.amazonaws.com' + '/'+ bucketname + '/' + 'demo.csv';

        HttpRequest req = new HttpRequest();
        req.setMethod(requestType);
        req.setHeader('Host','https://s3.amazonaws.com');
        req.setEndpoint(filePath);
        req.setHeader('Content-Length', String.valueOf(csvFile.length()));
        req.setHeader('Content-Type', contentType);
        req.setHeader('Date', formattedDateString);
        req.setHeader('ACL', 'public-read-write');
        Blob CSV = Blob.valueof(csvFile);
        req.setBodyAsBlob(CSV);

        String auth = createAuthHeader(requestType, contentType, filename, formattedDateString, bucketname, awsAccessKey, awsSecretKey);

        Http http = new Http();

        HTTPResponse res = http.send(req);
        System.debug('RESPONSE STRING: ' + res.toString());
        System.debug('RESPONSE STATUS: ' + res.getStatus());
        System.debug('STATUS_CODE: ' + res.getStatusCode());
    } catch(System.CalloutException e) {
        system.debug('AWS Service Callout Exception: ' + e.getMessage());
        system.debug('AWS Service Callout Exception: ' + e.getCause());
        system.debug('Exception: ' + e.getStackTraceString());
    } catch(Exception e) {
        system.debug('Exception: ' + e.getMessage());
        system.debug('Exception: ' + e.getStackTraceString());
    }  
}

public static String createAuthHeader(String method, String contentType, String filename, String formattedDateString, String bucket, String key, String secret){
    string auth;

    String stringToSign = method+'\n'+bucket+'/'+filename+'\n';
    Blob mac = Crypto.generateMac('HmacSHA1', blob.valueof(stringToSign), blob.valueof(secret));
    String sig = EncodingUtil.base64Encode(mac);
    auth = 'AWS' + ' ' + key + ':' + sig;


    return auth;
}  

我已按照此处的链接(https://developer.salesforce.com/forums/?id=906F0000000BMDFIA4)了解所使用的方法。

我可以使用AWS SDK将文件从ruby或javascript上传到同一个存储桶,但它给我的响应代码为400(错误请求)。 我认为这是签署请求过程中的一个问题。

如果有人可以帮助我,我们将非常感激。

1 个答案:

答案 0 :(得分:0)

这是一个link,它清楚地描述了AWS的身份验证过程。

http://gist.github.com/brianmfear/92cf05807ac4becbd21f