文件下载,文件名有中文及空格无法显示问题

原文链接:https://blog.csdn.net/zhoumengshun/article/details/72866210

使用response.setHeader(“Content-Disposition”,”attachment;filename=”+fName)下载文件, 
中文文件名无法显示的问题及空格处理

**该问题解决重点在于这两块代码**

//处理文件名有中文问题    
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
    file_name= URLEncoder.encode(fileName,"UTF-8");
} else {
    file_name= new String(fileName.getBytes(),"ISO-8859-1");
}


//最后加双引号处理名称中间有空格问题
response.setHeader("Content-Disposition","attachment;filename=\""+file_name+"\"");

代码如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author ZhouMengShun
 */
@Controller
@RequestMapping("/demo")
public class DemoController {

    @RequestMapping(value = "download", method = RequestMethod.GET)
    public void downloadFile(HttpServletRequest request,HttpServletResponse response) {

        InputStream in = null;
        try {
            String fileName="测试文件.rar";//文件名称
            File file = new File("c://"+fileName);//创建文件对象,假设该文件已存在,这里不做判断

            // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("application/x-msdownload");
            //response.setContentType("multipart/form-data");//也可以这样写

            String file_name=null;

            //处理文件名有中文问题    
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                file_name= URLEncoder.encode(fileName,"UTF-8");
            } else {
                file_name= new String(fileName.getBytes(),"ISO-8859-1");
            }

            //最后加双引号处理名称中间有空格问题
            response.setHeader("Content-Disposition","attachment;filename=\""+file_name+"\"");

            in = new FileInputStream(file);

            // 3.通过response获取ServletOutputStream对象(out)
            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = in.read(buffer);
                if (b != -1) {
                    response.getOutputStream().write(buffer, 0, b);// 4.写到输出流(out)中
                }
            }

        } catch (Exception e) {
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                response.getOutputStream().flush();
            } catch (Exception ex) {
            }
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值