如何读取直接触发lambda执行的上传文件?

时间:2017-10-18 08:15:03

标签: java amazon-web-services amazon-s3 lambda aws-lambda

我当前的AWS设置是一个lambda函数,只要我将对象放入S3存储桶就会触发该函数。我在Java中实现了lambda的处理函数。我想要做的只是访问上传的文件并触发lambda函数的执行。例如,如果我将sample.json上传到存储桶,我想在我的处理函数中访问该文件的内容。

我知道我可以这样做:

public Void handleRequest(S3Event input, Context context) {
  for (S3EventNotificationRecord record : input.getRecords()) {
    String key = record.getS3().getObject().getKey();
    String bucket = record.getS3().getBucket().getName();
    AmazonS3 s3Client = new AmazonS3Client(credentials);
    try {
      S3Object s3Object = s3Client.getObject(new GetObjectRequest(bucket, key));
      InputStream input = s3Object.getObjectContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
      while (true) {
        String line = reader.readLine();
        if (line == null) break;
        // Do something with line...
      }
// ...

问题是我不能使用访问密钥。因此,我无法创建s3Client来下载文件。换句话说,我必须从我的处理程序方法所采用的参数中获取对象,即S3Event input。我该怎么做?

1 个答案:

答案 0 :(得分:3)

如果您的Lambda函数配置了适当的IAM角色(允许s3:相关S3对象的GetObject),那么您不需要在代码中明确提供凭据。

以下示例Java代码,用于获取对象以响应上传的Lambda事件:

package example;

import java.net.URLDecoder;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord;

public class S3GetTextBody implements RequestHandler<S3Event, String> {

    public String handleRequest(S3Event s3event, Context context) {
        try {
            S3EventNotificationRecord record = s3event.getRecords().get(0);

            // Retrieve the bucket & key for the uploaded S3 object that
            // caused this Lambda function to be triggered
            String bkt = record.getS3().getBucket().getName();
            String key = record.getS3().getObject().getKey().replace('+', ' ');
            key = URLDecoder.decode(key, "UTF-8");

            // Read the source file as text
            AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient();
            String body = s3Client.getObjectAsString(bkt, key);
            System.out.println("Body: " + body);
            return "ok";
        } catch (Exception e) {
            System.err.println("Exception: " + e);
            return "error";
        }
    }
}