跳到主要內容

AWS S3 Java code samples

紀錄最近在處理 AWS 相關 issue 時用的部分 method
最基本的 download、upload等等還滿好在 AWS 上找到範例
不過似乎有些要求就沒那麼好找

從AWS下載檔案的檔案名稱(alias name)或其他 Header 調整

AWS示範了建立供下載使用的連結的範例

public static URL getURLPresigned(String bucket, String s3name) {
    AmazonS3 s3client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
    Date expire = new Date(new Date().getTime() + 86400000L);    // set to be available for 1 day.
    return s3client.generatePresignedUrl(bucket, s3name, expire, HttpMethod.GET);
}

但是會使用AWS的,絕大多數都是有大量檔案存取需求
應該有不少公司的做法也會是上傳的檔案會加上 hash
避免檔案被覆蓋或作為多版本紀錄用途
但是給使用者下載的檔案名稱還是要使用原先上傳時的才比較合理

一個可行的做法就是調整下載的回應的 Content-Disposition Header
這個 Header 可以用來設定下載的檔案名稱,規格的說明可以查看定義文件
寫出來的範例如下:

public static URL getURLPresigned(String bucket, String s3name, String contentDisposition) {
    AmazonS3 s3client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
    Date expire = new Date(new Date().getTime() + 86400000L);   // set to be available for 1 day.

    ResponseHeaderOverrides headers = new ResponseHeaderOverrides();
    headers.setContentDisposition(contentDisposition);
    GeneratePresignedUrlRequest greq = new GeneratePresignedUrlRequest(bucket, s3name, HttpMethod.GET);
    greq.withExpiration(expire);
    greq.withResponseHeaders(headers);

    return s3client.generatePresignedUrl(greq);
}

其他Header也能透過 ResponseHeaderOverrides 物件設定

取得 AWS 上目錄(或檔案)的檔案大小

AWS的檔案配置結構就跟 Linux 的機制一樣
上傳檔案的 key 可以用 /uploads/username/fileA、/uploads/username/fileB 這樣的路徑設定
之後用以下方法查詢 /uploads/username,就能得到兩個檔案加起來的大小

public static long getFileSize(String bucket, String prefix) {
    long total = 0;

    AmazonS3 s3client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
    ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(prefix);

    ObjectListing objectListing;
    do {
        objectListing = s3client.listObjects(listObjectsRequest);
        for (S3ObjectSummary objectSummary: objectListing.getObjectSummaries()) {
            total += objectSummary.getSize();
        }
        listObjectsRequest.setMarker(objectListing.getNextMarker());
    } while (objectListing.isTruncated());

    return total;
}

確認 AWS 檔案是否存在

public static boolean isValidFile(String bucketName, String path) {
    AmazonS3 s3client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
    boolean isValidFile = true;
    try {
        s3client.getObjectMetadata(bucketName, path);
    } catch (AmazonS3Exception s3e) {
        isValidFile = false;
    }

    return isValidFile;
}

留言