简体   繁体   English

Amazon S3上传文件并获取URL

[英]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?是否可以通过单个操作将 txt/pdf/png 文件上传到 Amazon S3 ,并获取上传的文件 URL 作为响应?

If so, is AWS Java SDK the right library that I need to add in my java struts2 web application? 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.请为此建议我一个解决方案。

No you cannot get the URL in single action but two :)不,您无法通过单个操作获取 URL,而是通过两个操作获取 :)

First of all, you may have to make the file public before uploading because it makes no sense to get the URL that no one can access.首先,您可能必须在上传之前将文件设为公开,因为获取没人可以访问的 URL 是没有意义的。 You can do so by setting ACL as Michael Astreiko suggested.您可以按照 Michael Astreiko 的建议通过设置 ACL 来实现。 You can get the resource URL either by calling getResourceUrl or getUrl .您可以通过调用getResourceUrlgetUrl来获取资源 URL。

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");

Note1: The different between getResourceUrl and getUrl is that getResourceUrl will return null when exception occurs.注1: getResourceUrlgetUrl的不同之处在于getResourceUrl 在异常发生时会返回null。

Note2: getUrl method is not defined in the AmazonS3 interface.注2: getUrl方法未在AmazonS3 接口中定义。 You have to cast the object to AmazonS3Client if you use the standard builder.如果您使用标准构建器,则必须将对象转换为 AmazonS3Client。

You can work it out for yourself given the bucket and the file name you specify in the upload request.根据您在上传请求中指定的存储桶和文件名,您可以自行解决。

eg if your bucket is mybucket and your file is named myfilename :例如,如果您的存储桶是mybucket并且您的文件名为myfilename

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

The s3 bit will be different depending on which region your bucket is in. For example, I use the south-east asia region so my urls are like:根据您的存储桶所在的区域, s3位会有所不同。例如,我使用东南亚区域,因此我的网址如下:

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

@hussachai and @Jeffrey Kemp answers are pretty good. @hussachai 和 @Jeffrey Kemp 的回答非常好。 But they have something in common is the url returned is of virtual-host-style, not in path style.但它们有一个共同点,即返回的 url 是虚拟主机样式,而不是路径样式。 For more info regarding to the s3 url style, can refer to AWS S3 URL Styles .有关 s3 url 样式的更多信息,请参阅AWS S3 URL 样式 In case of some people want to have path style s3 url generated.如果有些人想要生成路径样式 s3 url。 Here's the step.这是步骤。 Basically everything will be the same as @hussachai and @Jeffrey Kemp answers, only with one line setting change as below:基本上一切都与@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());

This will generate url like: https://s3.us-west-2.amazonaws.com/mybucket/myfilename这将生成如下网址: https : //s3.us-west-2.amazonaws.com/mybucket/myfilename

同样,如果您想通过 s3Client 链接,您可以在下面使用。

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

For AWS SDK 2+对于 AWS 开发工具包 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();

a bit old but still for anyone stumbling upon this in the future:有点旧,但仍然适用于将来遇到此问题的任何人:

you can do it with one line assuming you already wrote the CredentialProvider and the AmazonS3Client.假设您已经编写了 CredentialProvider 和 AmazonS3Client,您可以用一行来完成。

it will look like this:它看起来像这样:

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

and if you didn't wrote the CredentialProvider and the AmazonS3Client then just add them before getting the URL like this:如果您没有编写 CredentialProvider 和 AmazonS3Client ,则只需在获取 URL 之前添加它们,如下所示:

  CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
        getApplicationContext(),
        "POOL_ID", // Identity pool ID
        Regions.US_EAST_1 // Region
);

Below method uploads file in a particular folder in a bucket and return the generated url of the file uploaded.下面的方法上传存储桶中特定文件夹中的文件,并返回上传文件的生成网址。

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);
}
System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());

使用此代码,您可以检索已上传文件到 S3 存储桶的链接。

If you're using AWS-SDK, the data object returned contains the Object URL in data.Location如果您使用的是 AWS-SDK,则返回的data对象包含data.Location中的对象 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))

I realize this question was asked eons ago, but I stumbled across it while doing research for a blog post.我意识到这个问题是很久以前被问到的,但是我在为一篇博客文章做研究时偶然发现了这个问题。

For anyone looking to do this at the user level, I wrote a small tool yesterday that uploads a file to an S3 bucket, and then prints the link to it so you can see it's in there.对于希望在用户级别执行此操作的任何人,我昨天编写了一个小工具,将文件上传到 S3 存储桶,然后打印指向它的链接,以便您可以看到它在那里。

To make the file public before uploading you can use the #withCannedAcl method of PutObjectRequest :为了使文件上传市民可以使用之前#withCannedAcl的方法PutObjectRequest

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM