文件下载

转载自:http://yunsyz.blog.163.com/blog/static/8620494201311355746227/

java实现文件下载功能,自动弹出保存窗口

    public void download() {

        String filePath =this.queueService.getCsvFilePathById(id);//所要下载的文件路径,从数据库中查询得到,当然也可以直接写文件路径,如:C:\\Users\\Administrator\\Desktop\\csv\\号码_utf8_100.csv

        try {

            File file = new File(filePath);

            String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);//得到文件名

            fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");//把文件名按UTF-8取出并按ISO8859-1编码,保证弹出窗口中的文件名中文不乱码,中文不要太多,最多支持17个中文,因为header有150个字节限制。

            response.setContentType("application/octet-stream");//告诉浏览器输出内容为流

            response.addHeader("Content-Disposition","attachment;filename="+fileName);//Content-Disposition中指定的类型是文件的扩展名,并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的,点保存后,文件以filename的值命名,保存类型以Content中设置的为准。注意:在设置Content-Disposition头字段之前,一定要设置Content-Type头字段。

            String len = String.valueOf(file.length());

            response.setHeader("Content-Length", len);//设置内容长度

            OutputStream out = response.getOutputStream();

            FileInputStream in = new FileInputStream(file);

            byte[] b = new byte[1024];

            int n;

            while((n=in.read(b))!=-1){

                out.write(b, 0, n);

            }

            in.close();

            out.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值