简体   繁体   English

S3生成下载链接

[英]S3 generate download link

I'm having trouble generating a download link for an html file i'm uploading to aws s3 server. 我在生成要上传到AWS S3服务器的html文件的下载链接时遇到问题。 I am able to generate the link and access the file. 我能够生成链接并访问文件。 But what I want to happen is that when I click the link is for the file to be downloaded instead of opening it. 但是我想发生的是,当我单击链接时,是要下载文件而不是打开文件。

Here is and example of the url: 这是网址的示例:

https://wassap_app.s3.us-east-1.amazonaws.com/report/test.html

Below is the code for the method that does the upload: 以下是执行上传方法的代码:

public boolean uploadFile(String name) {
    try {
        this.client.putObject(new PutObjectRequest(bucketName, "report/" + name, this.file)
                .withCannedAcl(CannedAccessControlList.PublicRead));
        String url = client.getUrl(bucketName, "report/" + name).toExternalForm();
        System.out.println("################ Download File URL ################");
        System.out.println(url);
        System.out.println("###################################################");
        return true;
    } catch (AmazonServiceException ase) {
        return false;
    } catch (AmazonClientException ace) {
        return false;
    }

}

You can use the response-content-disposition query parameter as documented here . 您可以使用此处记录response-content-disposition查询参数。 Your URL will then look like: 您的网址将如下所示:

https://wassap_app.s3.us-east-1.amazonaws.com/report/test.html?response-content-disposition=attachment%3B%20filename%3D%22report.html%22

But the documentation also states: 但是文档还指出:

You must sign the request, either using an Authorization header or a pre-signed URL, when using these parameters. 使用这些参数时,必须使用授权标头或预签名的URL对请求进行签名。 They cannot be used with an unsigned (anonymous) request. 它们不能与未签名(匿名)请求一起使用。

To sign the request for the user you can use a presigned URL. 要为用户签名请求,可以使用预签名的URL。 I don't have a Java environment to test right now, but something like the following should work. 我现在没有要测试的Java环境,但是类似以下的内容应该可以工作。

GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, "report/" + name);
ResponseHeaderOverrides overrides = new ResponseHeaderOverrides();
overrides.setContentDisposition("attachment; filename=\"report.html\"");
req.setResponseHeaders(overrides);
URL url = this.client.generatePresignedUrl(req);
System.out.println(url);

Call this method: 调用此方法:

String url = client.getResourceUrl(bucketName, "report/" + name);

Hope this helps! 希望这可以帮助!

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

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