ajaxfileupload对于json格式处理的问题(firefox、ie)

来源:互联网 发布:软件欢迎界面 素材 编辑:程序博客网 时间:2024/04/27 14:16

使用环境:springMVC、spring、mybatis、firefox22、ie9、mysql 5、tomcat 6,操作系统:window7旗舰版

最近使用ajaxfileupload.js这个组件,在异步上传文件后遇到两个问题:

1、使用spring集成jackson插件,获取到的json格式的数据,ajaxfileupload会自动在前后加上<pre></pre>标记,导致json格式无法正确解析。

解决办法:

找到ajaxfileupload的源码,tyep=="json"的位置,修改如下:

[javascript] view plaincopyprint?
  1.                             if (type == "script")  
  2.     jQuery.globalEval(data);  
  3. // Get the JavaScript object, if JSON is used.  
  4. if (type == "json") {  
  5.     <span style="color:#FF0000;">if (data.startsWith("<pre>") && data.endsWith("</pre>")) {  
  6.         data = data.substr(5, data.length - 11);  
  7.         data = jQuery.parseJSON(data);  
  8.     } else {</span>  
  9.         eval("data = " + data);  
  10.     <span style="color:#FF0000;">}</span>  
  11. }  

即是去掉前后的标记,自己解析json数据。


2、需求:在获取到用户上传的excel文件,使用POI解析其中的内容,并写入内容的处理结果数据到excel,最后当数据解析完成后,将excel保存到服务器,并直接通知用户下载该文件(直接异步下载,弹出下载窗口)。

问题:在firefox下OK,在IE9下边,上传这一步,ie直接认为发送的是一个下载请求,直接弹出下载提示,下载的文件名为请求的action.do的名字。

问题分析:原来上传请求的action,发挥的是一个对象,通过jackson转换为json数据返回给前端,但ajaxfileupload无法识别这个数据,通过ie的断点调试,无法跟踪到发挥的数据到底是什么样的。而后台根本没有出现任何错误,前端也如此。后来,我将请求的action返回为一个string对象,严格按照json的格式拼装:

[java] view plaincopyprint?
  1. return "{\"success\" : \"" + true + "\"}";  

这样问题解决……但是很遗憾任然没有找出问题所在……


附上请求上传action方法的代码:

[java] view plaincopyprint?
  1. @RequestMapping("import")  
  2. @ResponseBody  
  3. public String importWordsFromExcel(MultipartHttpServletRequest request, HttpSession session) {  
  4.     try {  
  5.         MultipartFile excel = request.getFile("excel");  
  6.         LOG.debug("begin import words from excel file :" + excel.getOriginalFilename());  
  7.         InputStream in = excel.getInputStream();  
  8.         Workbook wb = null;  
  9.         try {  
  10.             // 2003 - 2007  
  11.             wb = new HSSFWorkbook(in);  
  12.             LOG.debug("using excel 2003/2007");  
  13.         } catch (OfficeXmlFileException e) {  
  14.             // 2007以后的版本  
  15.             OPCPackage pkg = OPCPackage.open(in);  
  16.             wb = new XSSFWorkbook(pkg);  
  17.             LOG.debug("using excel 2010 or higher version.");  
  18.         }  
  19.           
  20.         // 存放导入结果的列,无法实现  
  21.         int resultColIndex = 7;  
  22.         CellStyle failStyle = wb.createCellStyle();  
  23.         Font font = wb.createFont();  
  24.         font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
  25.         font.setColor(HSSFColor.RED.index);  
  26.         failStyle.setFont(font);  
  27.         CellStyle succStyle = wb.createCellStyle();  
  28.         font = wb.createFont();  
  29.         font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
  30.         font.setColor(HSSFColor.GREEN.index);  
  31.         succStyle.setFont(font);  
  32.           
  33.         Vocabulary v = null;  
  34.         Sheet sheet = wb.getSheetAt(0);  
  35.           
  36.         int totalColNum = 0;  
  37.         if (sheet.getRow(0) != null)  
  38.             totalColNum = sheet.getRow(0).getLastCellNum() - sheet.getRow(0).getFirstCellNum();  
  39.           
  40.         String sheetName = sheet.getSheetName();  
  41.         LOG.debug("current sheet name : " + sheetName);  
  42.         Cell cell = null;  
  43.         for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {  
  44.             Row row = sheet.getRow(rowNum);  
  45.             if (rowNum == 0) {  
  46.                 cell = row.createCell(resultColIndex);  
  47.                 cell.setCellValue("完成状态");  
  48.                 cell.setCellStyle(failStyle);  
  49.                 cell = row.createCell(resultColIndex + 1);  
  50.                 cell.setCellValue("说明");  
  51.                 cell.setCellStyle(failStyle);  
  52.                 continue;  
  53.             }  
  54.             v = new Vocabulary();  
  55.             for (int colNum = 0; colNum <= totalColNum; colNum++) {  
  56.                 cell = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK);  
  57.                 CellReference cellRef = new CellReference(rowNum, colNum);  
  58.                 LOG.debug("cell reference : " + cellRef.formatAsString());  
  59.                   
  60.                 String content = "";  
  61.                 if (cell.getCellType() == Cell.CELL_TYPE_STRING)  
  62.                     content = cell.getRichStringCellValue().getString().trim();  
  63.                 else if (cell.getCellType() == Cell.CELL_TYPE_BLANK)  
  64.                     content = "";  
  65.                 else {  
  66.                     continue;  
  67.                 }  
  68.                 switch (colNum) {  
  69.                 case 1// 单词  
  70.                     v.setWord(content);  
  71.                     break;  
  72.                 case 2// 美式发音  
  73.                     v.setSoundmark(content);  
  74.                     break;  
  75.                 case 3// 英式发音  
  76.                     v.setSoundmark2(content);  
  77.                     break;  
  78.                 case 4// 释义  
  79.                     v.setMeaning(content);  
  80.                     break;  
  81.                 case 5// 例句  
  82.                     v.setSentence(content);  
  83.                     break;  
  84.                 case 6// 例句释义  
  85.                     v.setSentenceMean(content);  
  86.                     break;  
  87.                 default:  
  88.                     break;  
  89.                 }  
  90.             }  
  91.             try {  
  92.                 Vocabulary tmpV = service.getByWord(v.getWord());  
  93.                 if (tmpV == null) {  
  94.                     // 保存到数据库  
  95.                     service.add(v);  
  96.                     cell = row.createCell(resultColIndex);  
  97.                     cell.setCellValue("成功");  
  98.                     cell.setCellStyle(succStyle);  
  99.                     cell = row.createCell(resultColIndex + 1);  
  100.                     cell.setCellValue("导入成功.");  
  101.                     // v.setStatus(Vocabulary.IMPORT_SUCCESS);  
  102.                     // v.setResult("导入成功.");  
  103.                 } else {  
  104.                     cell = row.createCell(resultColIndex);  
  105.                     cell.setCellValue("失败");  
  106.                     cell.setCellStyle(failStyle);  
  107.                     cell = row.createCell(resultColIndex + 1);  
  108.                     cell.setCellValue("单词已经存在.");  
  109.                     // v.setStatus(Vocabulary.IMPORT_FAIL);  
  110.                     // v.setResult("单词已存在.");  
  111.                 }  
  112.             } catch (Exception e) {  
  113.                 LOG.error("save words error : ", e);  
  114.                 cell = row.createCell(resultColIndex);  
  115.                 cell.setCellValue("失败");  
  116.                 cell.setCellStyle(failStyle);  
  117.                 cell = row.createCell(resultColIndex + 1);  
  118.                 cell.setCellValue("未知异常.");  
  119.                 // v.setStatus(Vocabulary.IMPORT_FAIL);  
  120.                 // v.setResult("未知异常.");  
  121.             }  
  122.         }  
  123.           
  124.         String originalFilename = excel.getOriginalFilename();  
  125.         User user = SystemUtil.getLoginUser(session);  
  126.         resultFilePath = request.getSession().getServletContext().getRealPath("/") + "/resource/tmp/"  
  127.                 + FilenameUtils.getBaseName(originalFilename) + "_导入结果_" + user.getName() + "."  
  128.                 + FilenameUtils.getExtension(originalFilename);  
  129.         FileOutputStream out = new FileOutputStream(resultFilePath);  
  130.         wb.write(out);  
  131.         out.close();  
  132.           
  133.         // GeneralMessage msg = new GeneralMessage();  
  134.         // msg.setCode(GeneralMessage.SUCCESS);  
  135.         // msg.setMsg("导入完成.");  
  136.         // return msg;  
  137.         return "{\"success\" : \"" + true + "\"}";  
  138.     } catch (Exception e) {  
  139.         LOG.error("import words error : ", e);  
  140.     }  
  141.     return null;  
  142. }  

下载结果文件的action方法:

[java] view plaincopyprint?
  1. @RequestMapping("downloadResultFile")  
  2.     @ResponseBody  
  3.     public ResponseEntity<byte[]> downloadUploadResult(HttpServletRequest request, HttpServletResponse response) {  
  4.         try {  
  5.             if (!StringUtils.hasLength(resultFilePath))  
  6.                 return null;  
  7.               
  8.             String fileName = FilenameUtils.getName(resultFilePath);  
  9.             //  
  10.             // HttpHeaders headers = new HttpHeaders();  
  11.             // headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
  12.             // headers.setContentDispositionFormData("attachment", new String(f.getBytes("UTF-8"),  
  13.             // "ISO-8859-1"));  
  14.             // return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new  
  15.             // File(fileAbsolutePath)), headers, HttpStatus.CREATED);  
  16.             File file = new File(resultFilePath); // 根据文件路径获得File文件  
  17.             // 设置文件类型(这样设置就不止是下Excel文件了,一举多得)  
  18.             response.setContentType("application/msexcel;charset=GBK");  
  19.               
  20.             // 文件名  
  21.             response.setHeader("Content-Disposition""attachment;filename=\"" + new String(fileName.getBytes("GBK"), "ISO-8859-1") + "\"");  
  22.             response.setContentLength((int) file.length());  
  23.             byte[] buffer = new byte[4096];// 缓冲区  
  24.             BufferedOutputStream output = null;  
  25.             BufferedInputStream input = null;  
  26.             try {  
  27.                 output = new BufferedOutputStream(response.getOutputStream());  
  28.                 input = new BufferedInputStream(new FileInputStream(file));  
  29.                 int n = -1;  
  30.                   
  31.                 while ((n = input.read(buffer, 04096)) > -1) {  
  32.                     output.write(buffer, 0, n);  
  33.                 }  
  34.                 output.flush(); // 不可少  
  35.                 response.flushBuffer();// 不可少  
  36.             } catch (Exception e) {  
  37.                 LOG.error("download upload words result file error : ", e);  
  38.             } finally {  
  39.                 if (input != null)  
  40.                     input.close();  
  41.                 if (output != null)  
  42.                     output.close();  
  43.             }  
  44.         } catch (Exception e) {  
  45.             LOG.error("download upload words result file error : ", e);  
  46.         }  
  47.         return null;  
  48.     }  

前端javascript中的处理:

[javascript] view plaincopyprint?
  1. function importFromExcel() {  
  2.     var excel = $("#excelFile").val();  
  3.     if (!excel || excel == ""  
  4.             || !(excel.endsWith("xls") || excel.endsWith("xlsx"))) {  
  5.         Error("未选择excel文件,请选择excel格式的文件后在进行导入操作.");  
  6.         return false;  
  7.     }  
  8.     $.ajaxFileUpload({  
  9.         url : Util.getContentPath() + '/word/import.do',  
  10.         secureuri : false,  
  11.         fileElementId : "excelFile",   
  12.         dataType : 'json',  
  13.         success : function(data, status) {  
  14.             var msg = data;  
  15.             if (msg && msg.success == "true") {  
  16.                 var callback = function() {  
  17.                     window.location.href = Util.getContentPath()  
  18.                             + "/word/downloadResultFile.do";  
  19.                 };  
  20.                 Alert("导入完成,可能有部分单词为成功导入!您需要下载<b>导入结果文件</b>来查看详细信息,点击确定后开始下载.",  
  21.                         callback);  
  22.             } else {  
  23.                 Error("批量导入出错.");  
  24.             }  
  25.         },  
  26.         error : function(data, status, e) {  
  27.             Error("批量导入出错.");  
  28.         }  
  29.     });  
  30.     return false;  
  31. }  
0 0
原创粉丝点击