Can't download file. Browser opens it instead.

孤人 提交于 2020-01-05 08:21:13

问题


I have tried a lot of contentTypes and headers I have seen here but still can't figure out what I am doing wrong. I have the following 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);
            }
        }
    }

I also have tried with and without @ResponseBody.

The user will be able to upload any type of file to the server and then he will be able to download through this controller. The problem is that instead of the download window, the browser open the file in the page. How can I make it download?

Thanks in advance


回答1:


This work for me:

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

}

Where MyFile is a class like this:

class MyFile {

  private Long id;

  private String contentType;

  private String name;

  private bit[] data;

  ...
}


来源:https://stackoverflow.com/questions/31408065/cant-download-file-browser-opens-it-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!