使用REST API将文件上传到s3存储桶

时间:2018-07-30 07:36:11

标签: java amazon-s3

使用S3 SDK进行此操作很简单。但是要使用S3 REST API(请阅读一些优点)。

我已经阅读了S3 API文档,发现很难使用它编写代码。我完全不熟悉这种类型的编码,它使用请求参数,请求标头,响应标头,授权,错误代码,ACL等。它还提供了示例示例,但找不到找到如何使用这些示例进行编码的方法。 / p>

任何人都可以从哪里开始和结束帮助,以便我可以使用API​​为S3上的所有CRUD操作编写代码。一个上传图像文件的示例将有助于我更好地理解。

2 个答案:

答案 0 :(得分:0)

如果您使用S3服务,您将更好地了解S3服务的工作原理,以下是一些示例示例,说明如何使用S3服务从S3服务器创建上载删除文件:-

1)how to use Amazon’s S3 storage with the Java API

2)S3 Docs

这里有简短的解释。

答案 1 :(得分:0)

我在下面放置了一些基本的代码片段,您可以轻松地将其集成到您的代码中。

获取s3客户端:

private AmazonS3 getS3Client() {
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(credentials)
            .withAccelerateModeEnabled(true).withRegion(Regions.US_EAST_1).build();
    return s3Client;
}

上传文件:

public void processOutput(FileServerDTO fileRequest) {

    try {
        AmazonS3 s3Client = getS3Client();
        s3Client.putObject(fileRequest.getBucketName(), fileRequest.getKey(), fileRequest.getFileContent(), null);
    } catch (Exception e) {
        logger.error("Exception while uploading file" + e.getMessage());
        throw e;
    }
}

下载文件:

public byte[] downloadFile(FileServerDTO fileRequest) {
    AmazonS3 s3Client = getS3Client();
    S3Object s3object = s3Client.getObject(new GetObjectRequest(fileRequest.getBucketName(), fileRequest.getKey()));
    S3ObjectInputStream inputStream = s3object.getObjectContent();
    try {
        return FileCopyUtils.copyToByteArray(inputStream);
    } catch (Exception e) {
        logger.error("Exception while downloading file" + e.getMessage());
    }
    return null;
}

FileServerDTO包含与文件信息有关的基本属性。 您可以在服务中轻松使用这些util方法。

相关问题