html部分:
<!-- 上传地图文件的弹出框 --> <div id="uploadMapFiledlg" class="easyui-dialog" style="width: 350px; height:180px;" closed="true" buttons="#upload-buttons" data-options="modal:true" > <form id="uploadMapFileForm" method="post" enctype="multipart/form-data" action="reportInfo/uploadMapFile.do"> <fieldset id="newMenuSet"> <table border="0px" cellspacing="1" cellpadding="1" > <tr style="line-height: 32px"> <td style="text-align: left;" ><label style="font-size: 12px;">上传文件:</label></td> <td style="text-align: left"> <input style="width: 220px; height: 25px" class="easyui-filebox" id="uploadfile" name="uploadfile" data-options="prompt:'只支持JSON格式...',buttonText:'选择文件...'"> </td> </tr> </table> </fieldset> </form> <div id="resultDiv2"> </div> <!--按钮部分--> <div id="upload-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-import" id="uploadBtn">上传</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" οnclick="javascript:$('#uploadMapFiledlg').dialog('close')">取消</a> </div> <!--弹出框按钮懒得复制了,在datagrid里-->
js代码:
//按钮部分 $(function(){ $("#uploadBtn").click(function(){ if($(this).linkbutton('options').disabled == false){ var file =$("#uploadfile").filebox('getValue'); if(file==""){ $.messager.alert('提示', '请先选择要上传文件!', 'info'); return; } var type=file.slice(file.lastIndexOf(".")+1,file.length); var checkType=type.toUpperCase(); if(checkType!=="JSON"){ $.messager.alert('提示', '所选的文件格式不正确!', 'info'); return; }; var uploadFileName=file.slice(file.lastIndexOf("\\")+1,file.length); $.ajax({ type: "post", url: contextPathName+"/reportInfo/cheackFile.do", data: {"uploadFileName":uploadFileName}, dataType: "json", success: function (data) { if(data.success){ if(data.isExists){ //用户确定覆盖? $.messager.confirm('确认对话框', data.fileMsg, function(r){ if (r){//覆盖(继续) virtualUpload(); }else{ //取消 var content ="<p>上传结果:</p>"; content +="<p>您取消了文件的上传</p>"; $('#resultDiv2').html(content); $('#uploadMapFileForm').form("reset"); return; } }); }else{//文件不存在 virtualUpload(); } } }, error:function(){ $.messager.alert('提示', "服务器发生错误!", 'info'); } }); } }); //显示上传地图文件窗口 $("#uploadMapFileBtn").click(function(){ if($(this).linkbutton('options').disabled == false){ $('#uploadMapFileForm').form("reset"); $('#resultDiv2').empty(); $('#uploadMapFiledlg').dialog('open').dialog('setTitle', '上传地图文件'); } }); }) //实际上传操作 function virtualUpload(){ var intervalId = null; var progressBar = null; var options = { dataType : "json", beforeSubmit : function() { $.messager.progress({ title:'请稍后', msg:'正在处理中...', }); }, complete:function(){ $.messager.progress('close'); }, success : function(data) { if(data.success){ $.messager.alert('提示', "操作成功", 'info'); var content ="<p>上传结果:</p>"; content +="<p>"+data.resultMsg+"</p>"; $('#resultDiv2').html(content); $('#uploadMapFileForm').form("reset"); }else{ $('#resultDiv2').empty(); $.messager.alert('提示', data.errorMsg, 'info'); } }, error : function(result) { $.messager.alert('提示', "服务器发生错误!", 'info'); } }; $('#uploadMapFileForm').ajaxSubmit(options); return !1; }
java后台(控制器里的)
//检查文件是否存在 @RequestMapping ("/cheackFile") @ResponseBody public String cheackFile (HttpServletResponse response, HttpServletRequest request) { Map <String, Object> data = new HashMap <String, Object> (); boolean result = Boolean.TRUE; // 定义容器接收文件名 String uploadFileName = null; try { String brProjectPath = request.getSession ().getServletContext ().getRealPath ("/"); uploadFileName = request.getParameter ("uploadFileName"); // 文件保存路径 String filePath = brProjectPath + "map\\" + uploadFileName; File date = new File (filePath); if (date.exists ()) { data.put ("isExists", Boolean.TRUE); data.put ("fileMsg", "文件已存在!是否覆盖!"); } else { data.put ("isExists", Boolean.FALSE); } } catch (Exception e) { _logger.error (e.getMessage (), e); result = Boolean.FALSE; data.put ("errorMsg", "文件上传失败!"); } data.put ("success", result); String jsonStr = JSONObject.fromObject (data).toString (); return jsonStr; } //接收上传文件 @RequestMapping ("/uploadMapFile") @ResponseBody public String doUploadMapFile (@RequestParam (value = "uploadfile", required = false) MultipartFile uploadfile, HttpServletRequest request) { Map <String, Object> data = new HashMap <String, Object> (); boolean result = Boolean.TRUE; // 定义容器接收文件名 String uploadFileName = null; try { InputStreamReader read = new InputStreamReader (uploadfile.getInputStream (), "utf-8");// 考虑到编码格式 BufferedReader bufferedReader = new BufferedReader (read); StringBuffer jsonContent = new StringBuffer (); String content = ""; while ((content = bufferedReader.readLine ()) != null) { jsonContent.append (content); } String brProjectPath = request.getSession ().getServletContext ().getRealPath ("/"); uploadFileName = uploadfile.getOriginalFilename (); // 文件保存路径 String filePath = brProjectPath + "map\\" + uploadFileName; File date = new File (filePath); FileOutputStream fop = null; fop = new FileOutputStream (date); byte[] contentInBytes = jsonContent.toString ().getBytes (); fop.write (contentInBytes); fop.flush (); fop.close (); read.close (); } catch (Exception e) { _logger.error (e.getMessage (), e); result = Boolean.FALSE; data.put ("errorMsg", "文件上传失败!"); } data.put ("success", result); data.put ("resultMsg", uploadFileName + "上传成功!"); String jsonStr = JSONObject.fromObject (data).toString (); return jsonStr; }
效果
点击上传按钮,弹出上传文件框
选择文件:
操作提示:
显示结果:
检测到同名文件,给用户提示:
取消上传后:
我所遇见的问题
1.js报错:ajaxSubmit不是一个函数!
这里你需要引入一个js文件:jQuery/jquery.form.js,值得注意的是你还要把它放在jQuery.js的后面应为form.js基于jQuery;
2.在页面上死活找不到这个form!请求也无疾而终;
这里我的确是被坑的.....这个页面是同事写的,我本来是俩加功能的,他的页面也有form标签,但他的form标签是这样的<form><form>,结果我的form就被他吃了....
我是找了好久代码的问题没找到问题,最后还是
老大帮忙找出来的.....额,感觉被人在后面捅了一刀,泪目啊!