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 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.

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post
NERV Open Source
Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.