首页 > 技术文章 > spring mvc 文件下载

stono 2015-05-19 14:07 原文

在controller中进行代码编写;

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest req)
            throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //解决中文名称乱码问题
        String filename = new String("你好.xls".getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachement", filename);
        String realpath = req.getSession().getServletContext()
                .getRealPath("/resources/upload/");
        String pathname = realpath + File.separator + "123";
        File file = new File(pathname);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

 

推荐阅读