no

How to download a file using REST api

Normally I create an interface when defining a REST api, this is useful when testing using Arquillian. To define a download file api we must...

Normally I create an interface when defining a REST api, this is useful when testing using Arquillian. To define a download file api we must define the method below in the interface.
@GET
@Path("/downloadFile")
ActionStatus downloadFile(@QueryParam("file") String file);

And then in the implementation we have:
public void downloadFile(String filePath) throws BusinessApiException {
 HttpServletResponse response = // see http://czetsuya-tech.blogspot.com/2017/09/how-to-access-httpservletrequest-and.html
 
 File file = new File(getProviderRootDir() + File.separator + filePath);
 if (!file.exists()) {
  // handle exception
 }

 try {
  FileInputStream fis = new FileInputStream(file);
  response.setContentType(Files.probeContentType(file.toPath()));
  response.setContentLength((int) file.length());
  response.addHeader("Content-disposition", "attachment;filename=\"" + file.getName() + "\"");
  IOUtils.copy(fis, response.getOutputStream());
  response.flushBuffer();
 } catch (IOException e) {
  // handle exception
 }
}

*Note: IOUtils is from apache commons.

Related

javaee-rest 2624354701385182923

Post a Comment Default Comments

item