无法下载文件。浏览器打开它。 [英] Can't download file. Browser opens it instead.

查看:172
本文介绍了无法下载文件。浏览器打开它。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我也尝试过和没有 @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?

提前感谢

推荐答案

对我来说这个工作:

@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是这样的类:

Where MyFile is a class like this:

class MyFile {

  private Long id;

  private String contentType;

  private String name;

  private bit[] data;

  ...
}

这篇关于无法下载文件。浏览器打开它。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆