1,利用io流下载文件

1,利用io流下载文件
@RestController
public class FileController {
    @GetMapping (value = "download")
    public String download(HttpServletResponse response, Model model) {
        //通过文件名找出文件的所在目录
        String URL = "C:/Users/Administrator/Desktop/计划.txt";
        //得到要下载的文件
        File file = new File(URL);
        //如果文件不存在
        if (!file.exists()) {
            //如果文件不存在,进行处理
            int i = 1 / 0;//系统会报错,除数不能为0.
            // return "modules/cms/front/themes/"+site.getTheme()+"/frontError";
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;
        //创建缓冲区
        byte[] b = new byte[1024];
        int len = 0;
        try {
            //读取要下载的文件,保存到文件输入流
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            response.setContentType("application/force-download");
            String filename = file.getName();
            //设置响应头,控制浏览器下载该文件
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.setContentLength((int) file.length());
            //循环将输入流中的内容读取到缓冲区当中      
            while ((len = inputStream.read(b)) != -1) {
                //输出缓冲区的内容到浏览器,实现文件下载
                outputStream.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值