原文链接:https://blog.youkuaiyun.com/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) {
}
}
}
}