Servlet下载文件解决中文文件名问题

package com.itcast.servlet;

import com.itcast.utils.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 1.点击服务器连接,提交服务器参数,下载的文件名
 * 2.获取文件名,找到文件的真是路径;
 * 文件中下载:头信息设置
 * 1.设置文件的媒体路径。
 * 2.设置文件附件形式。
 */
public class Servlet01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受参数
        String filename = req.getParameter("filename");
        //2.设置Context-Type
        ServletContext servletContext = getServletContext();
        String mimeType = servletContext.getMimeType(filename);
        resp.setHeader("Context-Type", mimeType);

        //3.将文件名进行编码,返回给浏览器
        String newFilename = DownLoadUtils.encodeFileName(req, filename);
        //4.设置Content-Disposition头,只有设置这个参数,浏览器才会将文件作为下载目标下载
        resp.setHeader("Content-Disposition", "attachment;filename=" + newFilename);

        //4.设置文件的InPutStream
        String realPath = servletContext.getRealPath("/download/" + filename);
        InputStream is = new FileInputStream(realPath);

        //5.获取输出流
        ServletOutputStream os = resp.getOutputStream();

        int len = 0;
        byte[] b = new byte[1024];

        while ((len = is.read(b)) != -1) {
            os.write(b, 0, len);
        }
        is.close();
        os.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

//转换工具类

package com.itcast.utils;

import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class DownLoadUtils {

    public static String encodeFileName(HttpServletRequest request, String fileName) {
        String name = "";

        String agent = request.getHeader("User-Agent");
        System.out.println(agent);
        try {
            if (agent.contains("Firefox")) {
                BASE64Encoder base64Encoder = new BASE64Encoder();
                name = "=?UTF-8?B?" + new String(base64Encoder.encode(fileName.getBytes("UTF-8"))) + "?=";
            } else {
                name = URLEncoder.encode(fileName, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //System.out.println(name);
        return name;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值