接下来需要在服务器上制作文件,并将其发送到客户端并打印。
@RequestMapping(value = "/some", method = RequestMethod.GET)
public void getFileForPrint(HttpServletResponse response,
@RequestParam(value = "id", required = true) Long id,
@RequestParam(value = "print", defaultValue = "false") Boolean print) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fname);
ServletOutputStream out = response.getOutputStream();
somefile.write(out);
Desktop.getDesktop.print(new File("download location browser"));}
}
如果你的意思是当你达到一个终点时,你想立即下载一个文件,那么下面的代码应该会对你有所帮助。
@RequestMapping(value = "/somePath", method = RequestMethod.GET)
@ResponseBody
public void getFileForPrint(HttpServletResponse response,
@RequestParam(value = "id", required = true) Long id,
@RequestParam(value = "print", defaultValue = "false") Boolean print) throws Exception {
String filename="nameOfFileWhenDownloaded.txt";
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename="" + filename + """);
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
osw.write(contentsOfTheFile);
osw.flush();
osw.close();
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error is sending file");
}
}