2022-3-18 SSM实现文件下载后台controller层实现代码

**

SSM实现文件下载后台controller层实现代码

**

方式一

 	@ResponseBody
    @RequestMapping("/downFile")
    public void download(HttpServletRequest req, HttpServletResponse resp,String filename) throws IOException {
        //获取文件的绝对路径名称
        String path = req.getSession().getServletContext().getRealPath("/") + filename;
        //转码,中文文件名要使用URLEncoder.encode方法进行编码
        filename = URLEncoder.encode(filename,"UTF-8");
        //设置文件下载头
        resp.addHeader("Content-Disposition", "attachment;filename=" + filename);
        //设置文件ContentType类型,这样设置会自动判断下载文件类型
        resp.setContentType("multipart/form-data");
        //读取要下载的文件,保存到文件输入流
        FileInputStream in = new FileInputStream(path);
        // 创建输出流
        OutputStream out = resp.getOutputStream();
        // 创建缓冲区 及 缓冲区的大小设置
        byte[] buf = new byte[1024];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while((len = in.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        //关闭文件输入流
        in.close();
        // 关闭输出流
        out.close();
    }

方式二

@ResponseBody
@RequestMapping("/downFile")
public void downloadFile(String filename,HttpServletRequest req, HttpServletResponse resp) throws IOException {
	//Step1 前台用超链接触发下载功能,将要下载的文件名作为请求参数带上
	<a href="${basePath}/user/downFile?filename=${user.yhtx}" id="pic_download">下载头像</a>
    // Step2 后台接收请求,先设置响应头,表明为下载请求
    resp.setHeader("Content-Disposition", "attachment;filename="+filename);
    // Step3 获取文件的在硬盘上的绝对路径
    String realPath = req.getServletContext().getRealPath("/");
    // Step4 利用FileUtils将文件转成byte数组
    File file = new File(realPath,filename);
    byte[] bytes = FileUtils.readFileToByteArray(file);
    // Step5 从相应对象中获取输出流,将byte数组写出
    ServletOutputStream os = resp.getOutputStream();
    os.write(bytes);
    // Step6 清除输出流的缓存、关闭输出流
    os.flush();
    os.close();
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值