Skip to content

Instantly share code, notes, and snippets.

@Saberko
Created June 9, 2017 02:50
Show Gist options
  • Save Saberko/cbd2086eeb507d6a2a83a0478e8b901f to your computer and use it in GitHub Desktop.
Save Saberko/cbd2086eeb507d6a2a83a0478e8b901f to your computer and use it in GitHub Desktop.
Test
@RequestMapping(value = "/template/{filename}", method = {RequestMethod.GET})
public ResponseEntity<byte[]> downloadTemplate(HttpServletRequest request, @PathVariable("filename") String filename) {
String prefix = request.getServletContext().getRealPath(ConstantsManager.EXCEL_TEMPLATE_PATH);
filename += ".xls";
String filepath = prefix + "/" + filename;
File file = new File(filepath);
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> entity = null;
try {
String utfFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", utfFileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
} catch (UnsupportedEncodingException e) {
log.error("Unable to down file with UnsupportedEncoding: " + filename);
e.printStackTrace();
} catch (IOException e) {
log.error("Failed to read the file to download: " + filename);
e.printStackTrace();
}
return entity;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment