How to download a file using REST api
Tech-Today

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.




- How To Download A File In Angular2
There are 2 ways I use to download a file with Angular2 or greater. For this example, we will use a Java REST service. The first approach would be taking advantage of the HTTP download, where the Angular side will just call a URL that will initiate the...

- Display A Byte[] Image From A Rest Web Service
This tutorial will not delve into angular nor will we discuss what a directive is. We will not try to explain what a rest web service is. Instead we will provide a demonstration via actual code, how we can consume a rest service from angular that returns...

- How To Upload A File In Rest Api
This is how I define the method: @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) ActionStatus uploadFile(@MultipartForm FileUploadForm form); And then the implementation: public ActionStatus uploadFile(FileUploadForm form) { File file...

- How To Zipped A File Or Directory In Java
There are times when we have to zipped a file or directory recursively in Java. This is how we do it: public static void zipFile(File file) throws IOException { byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream( file.getParent()...

- How To Download A File From The Server Using Javaee
The following snippet will accept a filename in the server's directory, set it as the content of the FacesContext for the user to download. public String downloadXMLInvoice(String fileName) { File file = new File(getXmlInvoiceDir().getAbsolutePath()...



Tech-Today








.