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...
https://www.czetsuyatech.com/2017/09/javaee-rest-download-file-using-rest.html
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.
And then in the implementation we have:
*Note: IOUtils is from apache commons.
@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.
Post a Comment