struts2+jquery+ajax实现上传校验实例
生活随笔
收集整理的這篇文章主要介紹了
struts2+jquery+ajax实现上传校验实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??? 一直以為ajax不能做上傳,直到最近看了一些文章。需要引入AjaxFileUploaderV2.1.zip,下載鏈接:http://pan.baidu.com/s/1i3L7I2T
代碼和相關配置如下:
?? js代碼:
<script>//ajax 無刷新上傳文件function ajaxFileUpload() {//判斷是否選擇文件if($("#uploadFile").val() == null || $("#uploadFile").val()==""){alert("請選擇需要上傳的文件!");return;}//判斷后綴名var filepath=$("#uploadFile").val();var extStart=filepath.lastIndexOf(".");var ext=filepath.substring(extStart,filepath.length).toUpperCase();if(".xls".toUpperCase() !=ext ){alert("只能上傳Excel97-2003工作簿文件(xls)");return false;}//判斷文件大小var file = $('#uploadFile').get(0).files[0];if (file) {var fileSize = 0;if (file.size > 2*1024 * 1024) {alert("上傳的文件大小不能超過2MB,請核對后重試!");return false;}}$("#loading").ajaxStart(function () {$(this).show();})//開始上傳文件時顯示一個圖片.ajaxComplete(function () {$(this).hide();});//文件上傳完成將圖片隱藏起來 $.ajaxFileUpload({url: '<%=request.getContextPath()%>/server/doUploadAndInsert.action',//用于文件上傳的服務器端請求地址secureuri: false,//一般設置為falsefileElementId: 'uploadFile',//文件上傳空間的id屬性 <input type="file" id="file" name="file" />dataType: 'json',//返回值類型 一般設置為jsonsuccess: function (result) {var msgBean = result;alert(msgBean.msgText);}});return false;}</script>
需要導入jquery星河ajaxfileupload.js,html代碼:
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery-1.7.2.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery-ui.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery.validate.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery.metadata.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>
<div id="page-content" class="clearfix" style="padding-top: 20"><form id="myform" enctype="multipart/form-data" method="post"action="<%=request.getContextPath()%>/server/doUploadAndInsert.action"><span style="font-size: 15px;"> 選擇文件<span style="color: #c91523">(*.xls格式)</span>: </span><input id="uploadFile" type="file" style="font-size: 15px" label="瀏覽" name="uploadFile" accept="application/xls"></file></form><input type="button" style="margin: 0 0 20 370;font-size: 15px" class="btn btn-large btn-pink save-right"value="導入" onclick="return ajaxFileUpload();"/></div>
struts2 配置:
<package name="server" extends="interceptorPackge" namespace="/server"><action name="doUploadAndInsert" class="serverBaseInfoAction" method="doUploadAndInsert" ><result type="plainText" /><param name="savePath">uploadTemp</param></action></package>
后端struts2 action代碼:
// 上傳文件所需屬性private String title;private File uploadFile;private String uploadFileContentType;private String SavePath;private String uploadFileFileName;Log log = LogFactory.getLog(this.getClass());public String doUploadAndInsert() throws Exception {PrintWriter out = null;MsgBean msg = new MsgBean();try {HttpServletResponse response = ServletActionContext.getResponse();response.setContentType("text/html;charset=utf-8");out = response.getWriter();if(getUploadFile().length()>2097152){msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");msg.setMsgText(getUploadFileFileName()+"上傳失敗,文件太大。\r\n請不要上傳超過2048KB的文件");out.write(JSON.toJSONString(msg));out.flush();return null;}//后綴名限制String suffixName = getUploadFileFileName().split("\\.")[1];if(!"xls".equalsIgnoreCase(suffixName)){msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");msg.setMsgText(getUploadFileFileName()+"上傳失敗,錯誤的文件格式!");out.write(JSON.toJSONString(msg));out.flush();return null;}UUID uuid = UUID.randomUUID();ServletContext servletContext = (ServletContext) ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);String rootPath = servletContext.getRealPath("/");File folder = new File(rootPath + "\\" + getSavePath());if (!folder.exists()) {folder.mkdir();}FileOutputStream fileOutputStream = new FileOutputStream(rootPath + "\\" + getSavePath() + "\\" + uuid+"_"+getUploadFileFileName());FileInputStream fileInputStream = new FileInputStream(getUploadFile());byte[] buffer = new byte[1024];int len = 0;while ((len = fileInputStream.read(buffer)) > 0) {fileOutputStream.write(buffer, 0, len);}fileInputStream.close();log.info("上傳文件接收成功,文件存放全路徑為:" + rootPath + "/" + uuid+"_"+getUploadFileFileName()); } catch (Exception e){msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");msg.setMsgText(getUploadFileFileName()+"上傳失敗,"+e.getMessage());out.write(JSON.toJSONString(msg));out.flush();} finally{out.close();return null;}}?
總結
以上是生活随笔為你收集整理的struts2+jquery+ajax实现上传校验实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET中利用DataList实现
- 下一篇: footer固定到底部