主题:Uploadify上传插件中文乱码问题解决方法

在使用Uploadify插件进行文件上传时,当上传的文件名包含中文时,则在后台读取时,会出现乱码问题。之前一直以为是插件自带Flash上传器中的代码没有对中文编码问题进行处理,但经过反复试验发现,与Flash无关。
出现乱码是因为Flash发送数据是以UTF-8的格式进行编码,而后台接受时没有做出处理导致的。下面的代码是后台文件接收的Servlet代码,其中的

Java代码 复制代码
  1. upload.setHeaderEncoding("utf-8");  
upload.setHeaderEncoding("utf-8");



即表示使用utf-8的编码格式处理数据,这样一来,上传中文文件名则不会出现乱码问题

Java代码 复制代码
  1. ServletContext servletContext = this.getServletConfig().getServletContext();   
  2. ApplicationContext appContext = WebApplicationContextUtils   
  3.         .getWebApplicationContext(servletContext);   
  4. String uploadFolder = (String) req.getParameter("folder");   
  5. String savePath = this.getServletConfig().getServletContext().getRealPath(uploadFolder);   
  6. savePath = savePath + "\\";   
  7.   
  8. File f1 = new File(savePath);   
  9. if (!f1.exists()){   
  10.     f1.mkdirs();   
  11. }   
  12.   
  13. DiskFileItemFactory fac = new DiskFileItemFactory();   
  14. ServletFileUpload upload = new ServletFileUpload(fac);   
  15. upload.setHeaderEncoding("utf-8");   
  16. List fileList = null;   
  17. try{   
  18.     fileList = upload.parseRequest(req);   
  19. catch (FileUploadException ex){   
  20.     return;   
  21. }   
  22. Iterator<FileItem> it = fileList.iterator();   
  23. String name = "";   
  24. String extName = "";   
  25. while (it.hasNext()){   
  26.     FileItem item = it.next();   
  27.     if (!item.isFormField()){   
  28.         name = item.getName();   
  29.         long size = item.getSize();   
  30.         String type = item.getContentType();   
  31.         if (name == null || name.trim().equals("")){   
  32.             continue;   
  33.         }   
  34.         //扩展名格式:.flv   
  35.         if (name.lastIndexOf(".") >= 0){   
  36.             extName = name.substring(name.lastIndexOf("."));   
  37.         }   
  38.         File file = null;   
  39.         String format = "yyyyMMddHHmmss";   
  40.         Random r = new Random();   
  41.         do{   
  42.             //生成随机文件名:日期+四位随机数   
  43.             int rannum = (int) (r.nextDouble() * (9999 - 1000 + 1)) + 1000;   
  44.             name = DateUtil.parseString(new Date(), format);   
  45.             name = name + rannum;   
  46.             file = new File(savePath + name + extName);   
  47.         } while (file.exists());   
  48.   
  49.         File saveFile = new File(savePath + name + extName);   
  50.         try{   
  51.             item.write(saveFile);   
  52.         } catch (Exception e){   
  53.             e.printStackTrace();   
  54.         }   
  55.     }   
  56. }   
  57. resp.getWriter().print(name + extName);  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值