将文件保存到桌面

时间:2014-07-09 03:24:16

标签: java java-ee spring-mvc

我希望用户看到保存窗口,这样他就可以在从邮件下载附件时保存他想要的地方。 弹簧控制器:

  @RequestMapping(value="/getFile", method = RequestMethod.GET)
        public ModelAndView getFile(HttpServletRequest request, HttpServletResponse response) {

             ModelAndView mav = new ModelAndView();
             //logic to get the data from database

}

感谢。

1 个答案:

答案 0 :(得分:0)

第一个答案

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(
    @PathVariable("file_name") String fileName, 
    HttpServletResponse response) {
    try {
      // get your file as InputStream
      InputStream is = ...;
      // copy it to response's OutputStream
      IOUtils.copy(is, response.getOutputStream());
      response.flushBuffer();
    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '" + fileName + "'");
      throw new RuntimeException("IOError writing file to output stream");
    }

}

第二个选项

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    byte[] documentBody = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(new MediaType("application", "pdf"));
    header.set("Content-Disposition",
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(documentBody.length);

    return new HttpEntity<byte[]>(documentBody, header);
}

第三个选项

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}