Java文件下载(excel)

本文介绍了三种不同的文件下载方法,包括使用Spring框架的ResponseEntity、通过Servlet拦截URL请求以及直接写入HttpServletResponse。每种方法都有其特点,适用于不同的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最简单的方法就是把文件链接写到a标签的href里,但是有人说了,这样会暴露服务器的文件路径,有风险- -

下面整理介绍几种通过代码实现的方法: 
1,

    @RequestMapping("download") 
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception {
        String fileName = request.getParameter("fileName");
        String path = request.getSession().getServletContext().getRealPath("")+File.separator+"WEB-INF"+File.separator+"download";
        File file = new File(path,fileName);
        HttpHeaders headers = new HttpHeaders();  
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
        headers.setContentDispositionFormData("attachment", fileName);  
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);  
    }  

spring里的方法,跟response无关。

2, 
web.xml中

<servlet-mapping>
        <servlet-name>DownloadServlet</servlet-name>
        <url-pattern>/files/*</url-pattern>
</servlet-mapping>
1
2
3
4
    public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp){
        String filepath = req.getRequestURI();
        int index = filepath.indexOf(Global.USERFILES_BASE_URL);
        if(index >= 0) {
            filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());
        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);
        try {
            FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
            resp.setHeader("Content-Type", "application/octet-stream");
            return;
        } catch (FileNotFoundException e) {
            req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
            req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
        }
    }

这个方法是通过servlet拦截url请求,如果匹配到相应的路径,则下载。

3,

@RequestMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request,HttpServletResponse response) {
        try {
                String filepath = ;//已存在的文件路径
                FileInputStream fis = null;
                OutputStream os = null;
                try {
                    String downLoadName = new String("导出.xls".getBytes("gbk"), "iso8859-1");
                    fis = new FileInputStream(filepath);
                    os = response.getOutputStream();// 取得输出流
                    response.reset();// 清空输出流
                    response.setHeader("Content-disposition",
                            "attachment; filename=" + downLoadName);// 设定输出文件头
                    response.setContentType("application/x-download;charset=GBK;");
                    byte[] mybyte = new byte[fis.available()];
                    int len = 0;
                    while ((len = fis.read(mybyte)) != -1) {
                        os.write(mybyte, 0, len);
                    }
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这个方法其实和法2类似,都是写到response中,只不过法2用FileCopyUtils.copy()简化了操作。
--------------------- 
原文:https://blog.youkuaiyun.com/leebin_20/article/details/52689884 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值