如何在spring mvc控制器中获取下载位置浏览器?

时间:2015-12-17 14:22:42

标签: java spring-mvc printing

接下来需要在服务器上发送文件以及发送到客户端并打印后才能解决问题。

@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"));}
}

1 个答案:

答案 0 :(得分:0)

如果您的意思是在达到终点时想要立即下载文件,那么以下代码可以为您提供帮助。

@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");
        }
}