• 文件通过流的方式下载时的文件名设置


    response.addHeader("Content-Disposition", "attachment;filename="); 

    这里的文件名最好用URLDecode.decode(fileName, "UTF-8")处理过,不然中文会有乱码

    Servlet例子:

    package com.cj.test1_10;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URLEncoder;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class Test9
     */
    @WebServlet("/Test9")
    public class Test9 extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        public Test9() {
            super();
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取文件的绝对路径
            String realPath = this.getServletContext().getRealPath("/就来中文.jpg");
            System.out.println("realPath:"+realPath);
            //获取要下载的文件名
            String fileName = realPath.substring(realPath.lastIndexOf("\")+1);
            System.out.println("fileName:"+fileName);
            //设置响应头,以下载的形式打开文件
            response.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
            //获取要下载的文件输入流
            InputStream in = new FileInputStream(realPath);
            int len = 0;
            //创建数据缓冲区
            byte [] buffer = new byte[1024];
            //创建输出流
            ServletOutputStream out = response.getOutputStream();
            while((len = in.read(buffer))>0){
                out.write(buffer, 0, len);
            }
        }
    
    }
  • 相关阅读:
    window.location.href问题,点击,跳转到首页
    JS indexOf() lastIndexOf()与substring()截取字符串的区别
    原来的方法增加参数时,必须为新增的参数加个默认值
    Chrome不支持本地Ajax请求解决?
    Smarty中{literal}的使用详解
    windows不能在本地计算机启动apache
    Apache虚拟主机配置
    wamp环境网站根目录更改
    Java 读书笔记 (十三) for each 循环
    Java 读书笔记 (十二) Java Character 类
  • 原文地址:https://www.cnblogs.com/cuijiade/p/9209463.html
Copyright © 2020-2023  润新知