js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中
ajaxfileupload.js
jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io }, createUploadForm: function(id, fileElementId) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).appendTo('body'); return form; }, addOtherRequestsToForm: function(form,data) { // add extra parameter var originalElement = $('<input type="hidden" name="" value="">'); for (var key in data) { name = key; value = data[key]; var cloneElement = originalElement.clone(); cloneElement.attr({'name':name,'value':value}); $(cloneElement).appendTo(form); } return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId); if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try { $(io).remove(); $(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try { // var io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) { // If you add mimetype in your response, // you have to delete the '<pre></pre>' tag. // The pre tag in Chrome has attribute, so have to use regex to remove var data = r.responseText; var rx = new RegExp("<pre.*?>(.*?)</pre>","i"); var am = rx.exec(data); //this is the desired data extracted var data = (am) ? am[1] : ""; //the only submatch or empty eval( "data = " + data ); } // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); if ( type == "application/json"){ var data = r.responseText; data = jQuery.parseJSON(jQuery(data).text()) } return data; } })
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE> <html> <head> <base href="<%=basePath%>"> <title>北斗救援平台</title> <jsp:include page="common/head.jsp"/> <link href="static/page/style/grzx.css" rel="stylesheet" type="text/css"> </head> <body> <div id="columnbanner"><img src="static/page/images/grzx/banner.jpg"></div> <div id="mainbox"> <jsp:include page="common/grzx_navigation.jsp"></jsp:include> <div id="rightbox"> <div id="big_title"> <p>首页 · 帮助中心 · 栏目名称</p> 我的轨迹 </div> <div id="grzx_wdgj"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <thead> <tr> <td width="60" align="center">编号</td> <td>轨迹名称</td> <td width="120" align="center"> </td> <td width="100" align="center">操作</td> </tr> </thead> <tbody id="content"> </tbody> </table> </div> <div id="big_title">新增轨迹</div> <div id="grzx_wdzl" style="border:1px solid #ccc;border-top:none; padding:20px; background:#f9f9f9;"> <table style="margin:0px;"> <tr> <td valign="top">轨迹名称:</td> <td><input type="text" name="NAME" id="NAME" style="width:250px;"></td> </tr> <tr> <td valign="top">上传附件:</td> <td><input type="file" name="upfile" id="file2" style="width:250px;"></td> </tr> <tr> <td valign="top"> </td> <td><button type="submit" onclick="getupfilerul();">确认保存</button></td> </tr> </table> </div> </div> <div class="clear"></div> </div> <jsp:include page="common/foot.jsp"></jsp:include> </body> <script type="text/javascript" src="static/js/ajaxfileupload.js"></script> <link href="static/page/script/colorbox/example4/colorbox.css" rel="stylesheet" type="text/css" /> <script src="static/page/script/colorbox/colorbox/jquery.colorbo.proadmin.js"></script> <script type="text/javascript"> //基本接口-获取文件上传url function getupfilerul(){ $.ajaxFileUpload({ url:'usertrail/canupload', fileElementId:'file2', data:{NAME:$("#NAME").val()}, //dataType:'json', dataType:'application/json', success:function(data,status){ if(status=="success"){ location.reload(); } }, error:function(data,status,e){ alert(e); } }); } //删除文件 function deleteTrail(obj){ $.post('usertrail/candeleteTrail',{USERTRAIL_ID:obj},function(data){ if(!data.status){ alert(data.message); return; } location.reload(); }); } //生成轨迹图 function toguiji(id){ $(".tyj").colorbox({innerWidth:800, title :'我的地址', href:'bdjy/grzx_gjxx?c='+id , innerHeight:600, iframe:true, escKey:false, overlayClose:false}); } $(function(){ $.post('usertrail/canfindByUserId',function(data){ if(!data.status){ alert(data.message); return; } var str=''; for(var i=0;i<data.data.length;i++){ str+='<tr>' +'<td align="center">01</td>' +'<td><span>'+data.data[i].NAME+'</span></td>' +'<td align="center"><a class="tyj" onclick="toguiji(\''+data.data[i].USERTRAIL_ID+'\')">生成轨迹图</a></td>' +'<td align="center"><a class="ckxx" href="javascript:void(0)" onclick="deleteTrail(\''+data.data[i].USERTRAIL_ID+'\')">删除</a></td>' +'</tr>'; } $('#content').html(str); }); }); </script> </html>
java
/** * 描述:上传文件,解析文件,存到数据库中,并且返回前台文件路径 * @param file * @return 文件地址 */ @RequestMapping(value="canupload",method=RequestMethod.POST) @ResponseBody public Object uploadimg(@RequestParam("upfile") MultipartFile file, @RequestParam("NAME") String NAME,HttpServletRequest request){ String ffile = DateUtil.getDays(), fileName = ""; Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> guijimap = new HashMap<String, Object>(); PageData pd = new PageData(); pd = this.getPageData(); if (null != file && !file.isEmpty()) { String filePath = PathUtil.getClasspath()+Const.CAROUSEL +ffile; fileName = FileUpload.fileUp(file, filePath, this.get32UUID()); map.put("url", ffile + "/" +fileName); //解析gpx Element element = null; CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation(); // 可以使用绝对路劲 // File f = new File("test.xml"); // documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件) DocumentBuilder db = null; DocumentBuilderFactory dbf = null; String jingdu = ""; String weidu = ""; try { // 返回documentBuilderFactory对象 dbf = DocumentBuilderFactory.newInstance(); // 返回db对象用documentBuilderFatory对象获得返回documentBuildr对象 db = dbf.newDocumentBuilder(); // 得到一个DOM并返回给document对象 Document dt = db.parse(f); // 得到一个elment根元素 element = dt.getDocumentElement(); // 获得根节点gpx System.out.println("根元素:" + element.getNodeName()); // 获得根元素下的子节点trk NodeList childNodes = element.getChildNodes(); // 遍历这些子节点 for (int i = 0; i < childNodes.getLength(); i++) { // 获得每个对应位置i的结点 Node node1 = childNodes.item(i); if ("trk".equals(node1.getNodeName())) { // 如果节点的名称为"trk",则遍历trk下的子节点 NodeList childNodes2 = node1.getChildNodes(); for (int m = 0; m < childNodes2.getLength(); m++) { // 获得每个对应位置i的结点 Node node2 = childNodes2.item(m); if ("trkseg".equals(node2.getNodeName())) { // 如果节点的名称为"trkseg",则遍历trk下的子节点 NodeList childNodes3 = node2.getChildNodes(); for (int z = 0; z < childNodes3.getLength(); z++) { // 获得每个对应位置i的结点 Node node3 = childNodes3.item(z); if ("trkpt".equals(node3.getNodeName())){ //经度 //System.out.println(node3.getAttributes().getNamedItem("lat").getNodeValue()); jingdu+=","+node3.getAttributes().getNamedItem("lat").getNodeValue(); //维度 //System.out.println(node3.getAttributes().getNamedItem("lon").getNodeValue()); weidu+=","+node3.getAttributes().getNamedItem("lon").getNodeValue(); // guijimap.put(node3.getAttributes().getNamedItem("lat").getNodeValue(), node3.getAttributes().getNamedItem("lon").getNodeValue()); } } } } } } jingdu = jingdu.substring(1); weidu = weidu.substring(1); guijimap.put("lat", jingdu); guijimap.put("lon", weidu); if(StringUtils.isBlank(NAME)){ NAME = ""; } Session session = Jurisdiction.getSession(); PageData bduser = (PageData) session.getAttribute("bduser"); pd.put("USERID", bduser.getString("BDUSER_ID")); pd.put("NAME", NAME); pd.put("TRAIL", JSONObject.fromObject(guijimap)+""); pd.put("USERTRAIL_ID", this.get32UUID()); //主键 pd.put("CREATEON", Tools.date2Str(new Date())); //根据名称去数据库查询,有则修改,没有新增 List<PageData> listUserTrail = usertrailService.findByName(pd); if(listUserTrail!=null &&listUserTrail.size()>0){ usertrailService.edittrail(pd); }else{ //新增名称,经度维度到数据库中 usertrailService.save(pd); } }catch (Exception e) { e.printStackTrace(); } }else{ map.put("url", ""); } return AppUtil.returnObject(pd, map); }
实现了,js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中