补10.20 Servlet 乱码问题 文件下载

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

常用字符集: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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值