Java file download example

 Here u can get the code for download any file from the specified path


Example:

 @GetMapping(value = "/api/dashboard/getTemplate", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)

    private ResponseEntity<byte[]> getFileTemplate(@RequestParam(value = "fileName", required = false) String fileName) throws IOException {


        File file = new File(templatePath + fileName);

        byte[] zippedData = toByteArray(new FileInputStream(file));

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.setContentDisposition(ContentDisposition.builder("attachment").filename(fileName).build());

        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        httpHeaders.setContentLength(zippedData.length);

        return ResponseEntity.ok().headers(httpHeaders).body(zippedData);

    }


Have any doubts comment here!


Happy learning 😝

Comments

Popular Posts