zoukankan      html  css  js  c++  java
  • [javaEE] response实现图片下载

    Servlet中的doGet()方法中

    获取FileInputStream对象,new出来,构造参数:String的文件路径

    得到文件路径,调用this.getServletContext().getRealPath(“这里是应用根路径”)

    调用HttpServletResponse对象的getOutputStream()方法,得到OutputStream对象

    正常读取和写入流

    输入流可以关闭,输出流不要关闭

    此时图片会直接显示出来,并没有出现下载

    使用http协议头Content-Disposition:attachment;filename=1.jpg

    调用HttpServletResponse对象的setHeader()方法,参数:keyvalue

    此时问题,http协议头里不允许有中文,会出错,编码是iso8859-1

    使用url编码方式解决,二进制转十六进制加上个%

    调用UrlEncoder.encode()方法,进行url编码,参数:String文本,编码”utf-8”

            response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("测试.jpg", "utf-8"));
            FileInputStream file=new FileInputStream(this.getServletContext().getRealPath("1.jpg"));
            OutputStream os=response.getOutputStream();
            
            byte[] b=new byte[1024];
            int len=0;
            while((len=file.read(b))!=-1){
                os.write(b,0,len);
            }
            file.close();

  • 相关阅读:
    图书排列
    L1-059 敲笨钟 (20 分)
    区间移位
    取球博弈
    poj 2456 Aggressive cows
    对局匹配
    发现环
    数字划分
    哥德巴赫分解
    把数组排成最小的数
  • 原文地址:https://www.cnblogs.com/taoshihan/p/5578560.html
Copyright © 2011-2022 走看看