无法下载文件。浏览器会打开它。

时间:2015-07-14 13:28:17

标签: spring-mvc download controller

我已经尝试过很多我在这里看过的内容类型和标题,但仍然无法弄清楚我做错了什么。我有以下Spring Controller:

    @RequestMapping(value = "/anexo/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> getAnexoById(@PathVariable int id, HttpServletResponse response) {
        Anexo a = anexoDAO.getAnexo(id);

        if (a == null)
            return new ResponseEntity<String>(HttpStatusMessage.NOT_FOUND, HttpStatus.NOT_FOUND);
        else {
            try {
                File dir = new File("temp");
                if (!dir.exists())
                    dir.mkdirs();              

                String filePath = dir.getAbsolutePath() + File.separator + a.getName();
                File serverFile = new File(filePath);
                FileInputStream fistream = new FileInputStream(serverFile);

                org.apache.commons.io.IOUtils.copy(fistream, response.getOutputStream());
                response.setHeader("Content-Disposition", "attachment; filename=" + a.getName());
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Length", String.valueOf(serverFile.length()));
                response.setHeader("Content-Transfer-Encoding", "binary");
                response.flushBuffer();
                System.out.println(response.toString());
                return new ResponseEntity<String>(HttpStatus.OK);
            } catch (IOException ex) {
                return new ResponseEntity<String>("Exception on getting file", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }

我也尝试过使用@ResponseBody

用户可以将任何类型的文件上传到服务器,然后他就可以通过此控制器下载。问题是,浏览器不是下载窗口,而是打开页面中的文件。我怎样才能下载?

提前致谢

1 个答案:

答案 0 :(得分:2)

这项工作对我来说:

@ResponseBody
void getOne(@PathVariable("id") long id, HttpServletResponse response) throws IOException {

    MyFile file = fileRepository.findOne(id);
    if(file == null) throw new ResourceNotFoundException();

    response.setContentType(file.getContentType());
    response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() +"\"");
    response.setContentLength(file.getData().length);

    FileCopyUtils.copy(file.getData(), response.getOutputStream());

}

MyFile是这样的一个类:

class MyFile {

  private Long id;

  private String contentType;

  private String name;

  private bit[] data;

  ...
}