· 6 years ago · Jun 21, 2019, 01:24 AM
1@GET
2 @Path("/pdfdownload")
3 @Produces("application/pdf")
4 public Response getFile() {
5 File file = new File('/pathToFile'); // in local
6
7 ResponseBuilder response = Response.ok((Object) file);
8 response.header("Content-Disposition", "attachment; filename=file.pdf");
9 return response.build();
10}
11
12@GET
13@Path("/pdfdownload")
14@Produces("application/pdf")
15public Response getFile2() {
16 final S3Object s3Object = getAmazonS3Object();// AWS S3
17 final S3ObjectInputStream s3is = s3Object.getObjectContent();
18
19final StreamingOutput stream = new StreamingOutput() {
20 @Override
21 public void write(OutputStream os) throws IOException, WebApplicationException {
22 byte[] read_buf = new byte[1024];
23 int read_len = 0;
24 while ((read_len = s3is.read(read_buf)) > 0) {
25 os.write(read_buf, 0, read_len);
26 }
27 os.close();
28 s3is.close();
29 }
30};
31
32ResponseBuilder response = Response.ok(stream);
33response.header("Content-Disposition", "attachment; filename=file.pdf");
34return response.build();
35}
36
37private S3Object getAmazonS3Object() {
38 AWSCredentials credentials = new BasicAWSCredentials("accesskey",
39 "secretkey");
40 try {
41 AmazonS3 s3 = new AmazonS3Client(credentials);
42 S3Object s3object = s3.getObject(new GetObjectRequest("bucketName", "filename_WithExtension"));
43 return s3object;
44 } catch (AmazonServiceException e) {
45 System.err.println(e.getErrorMessage());
46 System.exit(1);
47 }
48 System.out.println("Done!");
49 return null;
50}
51
52<dependency>
53 <groupId>com.sun.jersey</groupId>
54 <artifactId>jersey-server</artifactId>
55 <version>1.8</version>
56 </dependency>
57
58
59<dependency>
60 <groupId>com.amazonaws</groupId>
61 <artifactId>aws-java-sdk</artifactId>
62 <version>1.11.542</version>
63 </dependency>