使用AWS Lambda函数(Java)将文件上传到s3

时间:2018-07-30 21:43:01

标签: amazon-web-services react-native amazon-s3 aws-lambda

我目前正在使用AWS服务制作一个本机应用程序。我对AWS Service用例几乎没有疑问,我在用例中搜索并阅读了有关AWS服务的信息,但没有任何确切的解决方案。
这是我的问题
我必须将照片和视频存储到S3存储桶中。因此,我正在制作一个简单的移动应用程序,该应用程序可以从画廊获取照片和视频,并进行API调用以触发AWS Lambda函数(用Java编写)以将这些照片和视频上传到相应的S3存储桶中。但是我的问题是,每当我尝试使用AWS Lambda函数将所有这些照片和视频存储到S3存储桶中时,始终不会收到此类文件或目录异常。我知道收到此异常的原因,因为这些照片和视频仅在本地存储中可用,而在AWS云中不可用(参考Upload Image into AWS S3 bucket using Aws Lambda)。那么有什么办法可以克服这个错误?否则我需要获取EC2实例来存储所有照片和视频?

我的示例Lambda功能代码(将图像上传到S3存储桶)

package com.amazonaws.lambda.demo;
import java.io.File;
import java.io.IOException; 
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;

public class LambdaFunctionHandler implements RequestHandler<String, PutObjectResult> {
@SuppressWarnings("deprecation")
public PutObjectResult UploadFile(String imageURI) throws IOException {

PutObjectResult resultObj = new PutObjectResult();
AWSCredentials credentials = new BasicAWSCredentials("Ak", "Sk");
//String clientRegion = "region";
String bucketName = "bucket_name";
String fileObjKeyName = "sample_image_pic.jpg";

try {
    AmazonS3 s3Client = new AmazonS3Client(credentials);

    // Upload a file as a new object with ContentType and title specified.

    resultObj = s3Client.putObject(new PutObjectRequest(bucketName, fileObjKeyName, new File(imageURI)));
}
catch(AmazonServiceException e) {
    // The call was transmitted successfully, but Amazon S3 couldn't process 
    // it, so it returned an error response.
    e.printStackTrace();
}
catch(SdkClientException e) {
    // Amazon S3 couldn't be contacted for a response, or the client
    // couldn't parse the response from Amazon S3.
    e.printStackTrace();
}

return resultObj;
}

@Override
public PutObjectResult handleRequest(String imageURI, Context context) {

PutObjectResult result = null;
try {
    result = UploadFile(imageURI);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return result;
}

}

谢谢

0 个答案:

没有答案