补10.20 Servlet 乱码问题 文件下载

来源:互联网 发布:电脑秒挂抢红包软件 编辑:程序博客网 时间:2024/05/01 10:17
 

在计算机中,只有二进制的数据,不同字符对应二进制的规则,就是字符的编码。

常用字符集:Ascii码;iso8859-1码;gb2312和gbk;unicode;utf-8;

出现乱码的解决方案:

1、 以post方法提交的数据中有中文字符, 可以在获取请求参数值之前,调用request.setCharacterEncoding(“UTF-8”),指定请求正文使用的字符编码是UTF-8;

2、在向浏览器发送数据之前调用 response.setHeader("Content-Type", "text/html;charset=UTF-8");这是最好的一种解决方法

3、用OutputStream输出数字时出现乱码解决:response.getOutputStream().write((97+"").getBytes()); //97任意数字

4、response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
response.getOutputStream().write("中国".getBytes("UTF-8"))。

当下载以中文名称的文件时出现乱码的解决方案:

设置消息头

response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));

//URLEncoder.encode(String,String)方法是:使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式。

文件下载问题:

//文件下载,知道下载的资源
ServletContext context = this.getServletContext();
String path = context.getRealPath("/WEB-INF/classes/imagers/123.gif");
File file = new File(path);
InputStream is = new FileInputStream(file);
//response.setHeader("content-disposition","attachment;filename=" + file.getName());//乱码问题
response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
OutputStream os = response.getOutputStream();


byte buffer[] = new byte[1024];
int len=0;
while((len= is.read(buffer))!= -1){
os.write(buffer,0,len);

}
os.close();
is.close();