应用场景为,一个file选择上传一个xml,然后点击预览。此时是先上传xml到服务器,然后读取xml并格式化返回json数据,然后获取该json,加载到页面之后,用SyntaxHighlighter插件动态高亮该段上传的xml代码。关键代码如下:
首先是文件上传并重命名,随后把上传之后的文件格式化转为json。代码如下:
@RequestMapping(value = "fileUpload.s", method = RequestMethod.POST) // public String fileUpload(@RequestParam("file") MultipartFile file) { public void fileUpload(HttpServletResponse response,HttpServletRequest request) { WebResult result=new WebResult(); result.setResult(WebResult.WEB_RESULT_FAIL); MultipartHttpServletRequest multipartHttpServletRequest= (MultipartHttpServletRequest) request; // MultipartHttpServletRequest multipartHttpServletRequest= new DefaultMultipartHttpServletRequest(request); MultipartFile file=multipartHttpServletRequest.getFile("exmlPath"); String filename=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+file.getOriginalFilename().substring(file.getOriginalFilename().indexOf('.')); // 判断文件是否为空 if (!file.isEmpty()) { try { // 文件保存路径 String filePath = request.getSession().getServletContext().getRealPath("/") + getPicUpload()+ filename; File dirPath = new File(request.getSession().getServletContext().getRealPath("/") + getPicUpload()); if (!dirPath.exists()) { dirPath.mkdirs(); } // 转存文件 file.transferTo(new File(filePath)); // Resource res=new ServletContextResource(ContextLoader.getCurrentWebApplicationContext().getServletContext(),"/upload/type.xml"); Resource res=new ServletContextResource(request.getSession().getServletContext(),getPicUpload()+filename); InputStream stream=res.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(stream,"gbk")); String temp=null; StringBuffer sb=new StringBuffer(); temp=br.readLine(); while(temp!=null){ sb.append(temp); temp=br.readLine(); } try { JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8); result.setName(filename); result.setReason(XmlFormat.format(sb.toString())); result.setResult(WebResult.WEB_RESULT_SUCCESS); objectMapper.writeValue(generator, result); } catch (IOException e) { logger.error("Upload failed: JSON convertion error."); } } catch (Exception e) { // e.printStackTrace(); logger.error("文件上传错误!错误详情为:"+e.getLocalizedMessage()); } } }
格式化的代码如下:
public class XmlFormat { public static String format(String str){ // System.out.println(" str : " + str); SAXReader reader = new SAXReader(); // System.out.println(reader); // 注释:创建一个串的字符输入流 StringReader in = new StringReader(str); StringWriter out = null; try { Document doc = reader.read(in); // System.out.println(doc.getRootElement()); // 注释:创建输出格式 OutputFormat formater = OutputFormat.createPrettyPrint(); //formater=OutputFormat.createCompactFormat(); // 注释:设置xml的输出编码 formater.setEncoding("utf-8"); // 注释:创建输出(目标) out = new StringWriter(); // 注释:创建输出流 XMLWriter writer = new XMLWriter(out, formater); // 注释:输出格式化的串到目标中,执行后。格式化后的串保存在out中。 writer.write(doc); writer.close(); } catch (DocumentException e) { // e.printStackTrace(); return "xml格式错误,请仔细检查!详细信息为:"+e.getLocalizedMessage(); } catch (IOException e) { // e.printStackTrace(); return "上传IO错误,请仔细检查!详细信息为:"+e.getLocalizedMessage(); } // 注释:返回我们格式化后的结果 return out.toString(); } public static void main(String[] args) throws Exception { String head="<?xml version=\"1.0\" encoding=\"GBK\"?>"; String str = "<RequestData><HeadData><UserCode>sh1_admin</UserCode><UserName>sh1_admin</UserName><UserCompanyCode>3107</UserCompanyCode><UserCompanyName>上海分公司一部</UserCompanyName><RequestType>03</RequestType></HeadData><BodyData><ReportId>113100000033</ReportId><Insurant>a5rfg87</Insurant><NumberPlate>沪E78612</NumberPlate><EngineModel></EngineModel><CarVin></CarVin><AccidentDate>2011-02-25 15:07:00</AccidentDate><ReportDate>2011-02-25 15:07:00</ReportDate><Province>310000</Province><City>310100</City><District></District><AccidentPlace>1</AccidentPlace><AccidentLongitude></AccidentLongitude><AccidentLatitude></AccidentLatitude><SurveyLongitude></SurveyLongitude><SurveyLatitude></SurveyLatitude><SceneReportFlag></SceneReportFlag><Reporter></Reporter><ReporterTel></ReporterTel><SurveyPlace></SurveyPlace><OperatorId>3525</OperatorId><OperatorName>sh_admin</OperatorName><ReportDealId>30000800</ReportDealId><ReportDealName>江苏分公司</ReportDealName><CompanyName></CompanyName><CustomerTypeCode></CustomerTypeCode><ForcePolicyId>a5rfg87a5rfg87a5rfg87</ForcePolicyId><BizPolicyId></BizPolicyId><Index>0</Index><FieldName>5</FieldName></BodyData></RequestData>"; // System.out.println(str); format(str); } }
随后,页面上使用ajaxFileUpload插件,ajax上传选中的xml并接受服务端返回的json,代码如下:
jQuery.ajaxFileUpload({ url:'fileUpload.s', secureuri:false, fileElementId:'exmlPath', dataType:'JSON', success:function(data,status){ //多次选择文件上传时,需先清空xmlPre这个div的html内容,否则SyntaxHighlighter渲染之后的html不会变 jQuery("#xmlPre").html("<div><pre id='xmlcontnt' class='brush: xml;'></pre></div>"); jQuery("#xmlPre").removeAttr("style",""); jQuery("#xmlPre").removeAttr("class",""); //----------------------------------------------------------------------- data=jQuery.parseJSON(jQuery(data).text()); //转化ajaxFileUpload插件返回的json,它会包裹一个pre标签 if(data.result==0){ $("#xmlname").val(data.name); // alert(data.reason); // console.log(data.reason); $("#xmlcontnt").text(data.reason); //将json格式的xml放入页面空的div中 SyntaxHighlighter.highlight(); //调用插件的高亮方法,渲染高亮 jQuery("#xmlPre").dialog({ //高亮后的代码所在div页面,以弹出层方式弹出,用以预览 minHeight: 300, width: 650, position: "top", title: "上传xml预览" }); jQuery("#xmlPre").dialog('open'); // $('.theme-popover-mask').fadeIn(100); // $('.theme-popover').slideDown(200); }else if(data.result==1){ alert("上传失败!"); }else{ alert("未知错误!"); } }, error:function (s, xml, status, e) { alert(s, xml, status, e) } });
弹出层的页面代码:
<div id="xmlPre" style="display:none;border: 1"> <pre > <pre id="xmlcontnt" class="brush: xml;"> </pre> </pre> </div>
SyntaxHighlighter2.1.364动态代码高亮
时间: 2024-10-18 21:53:15