无法下载文件。 浏览器打开它来代替。(Can't download file. Brow

2019-10-23 20:46发布

我已经尝试了很多CONTENTTYPES,我在这里看到的标头,但仍无法弄清我做错了。 我有以下春天控制器:

    @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

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

提前致谢

Answer 1:

这项工作对我来说:

@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;

  ...
}


文章来源: Can't download file. Browser opens it instead.