Amazon S3 upload file and get URL

Is it possible to upload a txt/pdf/png file to Amazon S3 in a single action, and get the uploaded file URL as the response?

If so, is AWS Java SDK the right library that I need to add in my java struts2 web application?

Please suggest me a solution for this.

165116 次浏览

您可以根据桶和在上传请求中指定的文件名自己解决这个问题。

例如,如果你的 bucket 是 mybucket,你的文件名为 myfilename:

https://mybucket.s3.amazonaws.com/myfilename

s3位将根据您的存储桶所在的区域而有所不同。例如,我使用东南亚地区,所以我的网址是这样的:

https://mybucket.s3-ap-southeast-1.amazonaws.com/myfilename

要在上传前公开该文件,可以使用 PutObjectRequest#withCannedAcl方法:

myAmazonS3Client.putObject(new PutObjectRequest('some-grails-bucket',  'somePath/someKey.jpg', new    File('/Users/ben/Desktop/photo.jpg')).withCannedAcl(CannedAccessControlList.PublicRead))


String url = myAmazonS3Client.getUrl('some-grails-bucket',  'somePath/someKey.jpg').toString();

不,你不能单独获得 URL,而是两个:)

首先,您可能必须在上传之前公开该文件,因为获取没有人可以访问的 URL 是没有意义的。您可以按照 Michael Astreiko 的建议设置 ACL。 You can get the resource URL either by calling getResourceUrl or getUrl.

AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder.defaultClient();
s3Client.putObject(new PutObjectRequest("your-bucket", "some-path/some-key.jpg", new File("somePath/someKey.jpg")).withCannedAcl(CannedAccessControlList.PublicRead))
s3Client.getResourceUrl("your-bucket", "some-path/some-key.jpg");

注一: getResourceUrlgetUrl的不同之处在于,当发生异常时,getResourceUrl 将返回 null。

Note2: AmazonS3接口中没有定义 getUrl方法。如果使用标准构建器,则必须将对象强制转换为 AmazonS3Client。

有点老了,但对于任何将来偶然发现这一点的人来说仍然是:

假设您已经编写了 CredentialProvider 和 AmazonS3Client,那么只需要一行代码就可以完成。

它会是这样的:

 String ImageURL = String.valueOf(s3.getUrl(
ConstantsAWS3.BUCKET_NAME, //The S3 Bucket To Upload To
file.getName())); //The key for the uploaded object

如果你没有编写 CredentialProvider 和 AmazonS3Client,那么只要在得到这样的 URL 之前添加它们:

  CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"POOL_ID", // Identity pool ID
Regions.US_EAST_1 // Region
);
System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());

通过这段代码,您可以检索已经上传的文件到 S3 bucket 的链接。

类似地,如果您希望通过 s3Client 进行链接,可以在下面使用。

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

@ Hussachai 和@Jeffrey Kemp 的答案都很好。但是它们有一个共同点,那就是返回的 URL 是虚拟主机风格的,而不是路径风格的。关于 s3url 样式的更多信息,可以参考 AWS S3 URL 样式。如果有些人想有路径样式 s3url 生成。这是台阶。基本上所有问题的答案都和@hussachai 和@Jeffrey Kemp 的答案一样,只是换了一行如下:

AmazonS3Client s3Client = (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion("us-west-2")
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
.withPathStyleAccessEnabled(true)
.build();


// Upload a file as a new object with ContentType and title specified.
PutObjectRequest request = new PutObjectRequest(bucketName, stringObjKeyName, fileToUpload);
s3Client.putObject(request);
URL s3Url = s3Client.getUrl(bucketName, stringObjKeyName);
logger.info("S3 url is " + s3Url.toExternalForm());

这将生成如下 URL: https://s3.us-west-2.amazonaws.com/mybucket/myfilename

下面的方法将文件上传到桶中的特定文件夹中,并返回上传文件的生成 URL。

private String uploadFileToS3Bucket(final String bucketName, final File file) {
final String uniqueFileName = uploadFolder + "/" + file.getName();
LOGGER.info("Uploading file with name= " + uniqueFileName);
final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uniqueFileName, file);
amazonS3.putObject(putObjectRequest);
return ((AmazonS3Client) amazonS3).getResourceUrl(bucketName, uniqueFileName);
}

用于 AWS SDK 2 +

String key = "filePath";
String bucketName = "bucketName";
PutObjectResponse response = s3Client
.putObject(PutObjectRequest.builder().bucket(bucketName ).key(key).build(), RequestBody.fromFile(file));
GetUrlRequest request = GetUrlRequest.builder().bucket(bucketName ).key(key).build();
String url = s3Client.utilities().getUrl(request).toExternalForm();

如果您正在使用 AWS-SDK,返回的 data对象包含 data.Location中的 Object URL

const AWS = require('aws-sdk')
const s3 = new AWS.S3(config)


s3.upload(params).promise()
.then((data)=>{
console.log(data.Location)
})
.catch(err=>console.log(err))