关于spring mvc web工程上传下载中文文件出现乱码的问题

*****为服务器的编码方式

1.MultipartFile上传文件

       目的路径需要按照服务器的地址进行编码:

             filename = new String( filename .getBytes("utf-8") , "*****");

            FileUtils.copyInputStreamToFile(myfile.getInputStream(),
new File(destPath, filename));

2.下载文件

         文件存放路径需要按照服务器的地址进行编码:

              filePath = new String(filePath.getBytes("utf-8"), "*****");

        下载时:

            response.setContentType("application/octet-stream;charset=utf-8");

            //filename为下载文件的中文名字

            String tempStr = new String(filename.getBytes("utf-8"), "*****");

            response.addHeader("Content-Disposition","attachment;filename=" + new String(tempStr.getBytes("*****"),"iso-8859-1"));


              OutputStream outp = null;
      FileInputStream in = null;
    try{
    in = new FileInputStream(filePath);
   outp = response.getOutputStream();
   byte[] b = new byte[1024];
   int i = 0;
   while((i = in.read(b)) > 0){
       outp.write(b, 0, i);
   }
   outp.flush();
   outp.close();
   outp=null;
   response.flushBuffer();
   
   logger.info("no error " );
     }catch(FileNotFoundException e){
   System.out.println("Error!!");
   logger.info("FileNotFoundException e: " + e);
   e.printStackTrace();
   session.setAttribute("fileDownload", 0);
     }
    finally{
if(in != null){
in.close();
in = null;
}
if(outp != null){
outp.close();
outp = null;
   }
}
}


3.从js向后台传递中文参数

        JSP的JS中:中文参数用encodeURI(encodeURI(中文参数)),经过两次转码。例如: 

复制代码 代码如下:

function show(next,id,realName){ 
document.forms['f2'].action="usersearchNextPage?next="+next+"&id="+id+"&realName="+encodeURI(encodeURI(realName)); 
document.forms['f2'].submit(); 


       其中 realName是中文参数。故在提交的URL中将realName转码两次。encodeURI(encodeURI(realName)) 

        Action中:接收中文参数时解码。用:java.net.URLDecoder.decode(realName,"UTF-8"); 

       如: 
复制代码 代码如下:

String realName = ServletActionContext.getRequest().getParameter("realName"); 
try { 
realName = java.net.URLDecoder.decode(realName,"UTF-8"); 
} catch (UnsupportedEncodingException e1) { 
e1.printStackTrace(); 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值