zoukankan      html  css  js  c++  java
  • 文件通过流的方式下载时的文件名设置

    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);
            }
        }
    
    }
  • 相关阅读:
    IOS:接口返回包含转义字符去掉转义字符
    properties和yml进行对比
    IDEA安装插件时搜索不到,一直在转圈刷新,无法安装
    VMware 15 虚拟机黑屏问题
    扩容根分区
    CentOS 6 各种启动文件损坏及修复
    RabbitMQ面试题
    FTP,SFTP服务器登录权限和根目录的设置
    Tee命令的几个使用实例
    ssh-copy-id 后无法免密登录
  • 原文地址:https://www.cnblogs.com/cuijiade/p/9209463.html
Copyright © 2011-2022 走看看