简体   繁体   中英

S3 generate download link

I'm having trouble generating a download link for an html file i'm uploading to aws s3 server. 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 . 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. They cannot be used with an unsigned (anonymous) request.

To sign the request for the user you can use a presigned URL. I don't have a Java environment to test right now, but something like the following should work.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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