生成预签名URL
您可以利用 GeneratePresignedUrl 接口为一个对象生成一个预签名的URL链接。通过访问该链接即可下载该对象。
String bucketName = "<your-bucket-name>";
String objectKey = "<your-object-key>";
try {
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.GET)
.withExpiration(expiration);
URL url = s3.generatePresignedUrl(request);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
}
如果需要在URL中添加额外参数,可以使用addRequestParameter接口
String bucketName = "<your-bucket-name>";
String objectKey = "<your-object-key>";
try {
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.GET)
.withExpiration(expiration);
// 在URL中添加额外参数
request.addRequestParameter("x-amz-limit", String.format("rate=%d", 100));
request.addRequestParameter("x-amz-process", "image/watermark,text_12345678");
URL url = s3.generatePresignedUrl(request);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
}
您可以利用 GeneratePresignedUrl 接口为一个对象生成一个预签名的URL链接,通过该链接可上传对象。
String bucketName = "<your-bucket-name>";
String objectKey = "<your-object-key>";
LocalDateTime expirationDateTime = LocalDateTime.now().plusSeconds(5 * 60);//url的有效时间5分钟
Date expiration = Date.from(expirationDateTime.atZone(ZoneId.systemDefault()).toInstant());
try {
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
URL url = s3.generatePresignedUrl(generatePresignedUrlRequest);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
}
参数如下,
参数 | 类型 | 描述 |
---|---|---|
bucketName | String | 桶名 |
key | String | 对象名 |
expiration | Date | 过期时间,默认900秒 |