有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在上传到AWS S3 bucket时更改文件名

我正在尝试将csv文件上传到S3 bucket。代码运行成功,但当我检查bucket时,以Access Key作为名称的文件被上传。我必须手动重命名该文件以检查其内容

有没有一种方法可以让我只以编程方式重命名文件,或者文件名在上传时不会自动更改

请检查以下代码:

public class AwsFileUploader {

private static String bucketName = "mybucket";
private static String accessKey = "my-access-key";
private static String secretKey = "my-secret-key";
private static String uploadFileName = "CompressionScore/compression_score_09-04-2015.csv";

public static void main(String[] args) throws IOException {

    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

    AmazonS3 s3client = new AmazonS3Client(credentials);

    try {
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        System.out.println(file.getName());   //prints - compression_score_09-04-2015.csv
        s3client.putObject(new PutObjectRequest(bucketName, accessKey, file));
        System.out.println("File successfully uploaded");
    } catch (AmazonServiceException ase) {
        ase.printStackTrace();
    } catch (AmazonClientException ace) {
        ace.printStackTrace();
    }
}

}

理想情况下,bucket中的文件应该是compression_score_09-04-2015.csv,而不是它的AKAJI3EBMILBCWENUSA。 有人能告诉我该怎么做吗


共 (1) 个答案

  1. # 1 楼答案

    在PutObjectRequest构造函数中,key参数实际上是上传文件的名称,而不是访问密钥

    来自SDK文档:

    Parameters: bucketName - The name of an existing bucket to which the

    new object will be uploaded.

    key - The key under which to store the new object.

    input - The stream of data to upload to Amazon S3. metadata - The object metadata.

    At minimum this specifies the content length for the stream of data being uploaded.

    资料来源:PutObjectRequest constructor detail

    您不必在这里指定accessKey,因为您已经用包含访问密钥和密钥的凭据实例化了AmazonS3Client对象