在使用Uploadify插件进行文件上传时,当上传的文件名包含中文时,则在后台读取时,会出现乱码问题。之前一直以为是插件自带Flash上传器中的代码没有对中文编码问题进行处理,但经过反复试验发现,与Flash无关。 
出现乱码是因为Flash发送数据是以UTF-8的格式进行编码,而后台接受时没有做出处理导致的。下面的代码是后台文件接收的Servlet代码,其中的 
- upload.setHeaderEncoding("utf-8");??
 
upload.setHeaderEncoding("utf-8");
即表示使用utf-8的编码格式处理数据,这样一来,上传中文文件名则不会出现乱码问题 
- ServletContext?servletContext?=?this.getServletConfig().getServletContext(); ??
 - ApplicationContext?appContext?=?WebApplicationContextUtils ??
 - ????????.getWebApplicationContext(servletContext); ??
 - String?uploadFolder?=?(String)?req.getParameter("folder"); ??
 - String?savePath?=?this.getServletConfig().getServletContext().getRealPath(uploadFolder); ??
 - savePath?=?savePath?+?"\\"; ??
 - ??
 - File?f1?=?new?File(savePath); ??
 - if?(!f1.exists()){ ??
 - ????f1.mkdirs(); ??
 - } ??
 - ??
 - DiskFileItemFactory?fac?=?new?DiskFileItemFactory(); ??
 - ServletFileUpload?upload?=?new?ServletFileUpload(fac); ??
 - upload.setHeaderEncoding("utf-8"); ??
 - List?fileList?=?null; ??
 - try{ ??
 - ????fileList?=?upload.parseRequest(req); ??
 - }?catch?(FileUploadException?ex){ ??
 - ????return; ??
 - } ??
 - Iterator<FileItem>?it?=?fileList.iterator(); ??
 - String?name?=?""; ??
 - String?extName?=?""; ??
 - while?(it.hasNext()){ ??
 - ????FileItem?item?=?it.next(); ??
 - ????if?(!item.isFormField()){ ??
 - ????????name?=?item.getName(); ??
 - ????????long?size?=?item.getSize(); ??
 - ????????String?type?=?item.getContentType(); ??
 - ????????if?(name?==?null?||?name.trim().equals("")){ ??
 - ????????????continue; ??
 - ????????} ??
 - ????????//扩展名格式:.flv ??
 - ????????if?(name.lastIndexOf(".")?>=?0){ ??
 - ????????????extName?=?name.substring(name.lastIndexOf(".")); ??
 - ????????} ??
 - ????????File?file?=?null; ??
 - ????????String?format?=?"yyyyMMddHHmmss"; ??
 - ????????Random?r?=?new?Random(); ??
 - ????????do{ ??
 - ????????????//生成随机文件名:日期+四位随机数 ??
 - ????????????int?rannum?=?(int)?(r.nextDouble()?*?(9999?-?1000?+?1))?+?1000; ??
 - ????????????name?=?DateUtil.parseString(new?Date(),?format); ??
 - ????????????name?=?name?+?rannum; ??
 - ????????????file?=?new?File(savePath?+?name?+?extName); ??
 - ????????}?while?(file.exists()); ??
 - ??
 - ????????File?saveFile?=?new?File(savePath?+?name?+?extName); ??
 - ????????try{ ??
 - ????????????item.write(saveFile); ??
 - ????????}?catch?(Exception?e){ ??
 - ????????????e.printStackTrace(); ??
 - ????????} ??
 - ????} ??
 - } ??
 - resp.getWriter().print(name?+?extName);??
 
    1 楼
    a498740995
    2012-04-23  
    
    
  
  我单步跟了下,Flash发送数据是以iso-8859-1格式进行编码,怎么改能utf-8呢?
中午按钮已经解决了。。
中午按钮已经解决了。。
    2 楼
    a498740995
    2012-04-23  
    
    
  
  fileItem 里获取的文件类型是:application/octet-stream
怎么改啊?
怎么改啊?