使用Ajax進(jìn)行文件與其他參數(shù)的上傳功能(java開發(fā))
文件上傳:
記得前一段時(shí)間,為了研究Ajax文件上傳,找了很多資料,在網(wǎng)上看到的大部分是form表單的方式提交文件,對(duì)于Ajax方式提交文件并且也要提交表單中其他數(shù)據(jù),發(fā)現(xiàn)提及的并不是很多,后來在同事的幫助下,使用ajaxfileupload最終完成了文件上傳與其他提交的操作,現(xiàn)在分享給大家,希望大家能有有所幫助。
操作步驟:
1 導(dǎo)入jar包:
我們在使用文件上傳時(shí),需要使用到兩個(gè)jar包,分別是commons-io與commons-fileupload,在這里我使用的兩個(gè)版本分別是2.4與1.3.1版本的,需要使用JS文件與jar包最后會(huì)發(fā)給大家一個(gè)連接(如何失效請直接我給留言,我會(huì)及時(shí)更改,謝謝)。
2 修改配置文件:
當(dāng)我們導(dǎo)入的jar包是不夠的,我們需要使用到這些jar包,由于我當(dāng)時(shí)使用的是SSM框架,所以我是在application-content.xml中配置一下CommonsMultipartResolver,具體配置方法如下:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>
3 JSP文件:
大家對(duì)form表單提交問價(jià)的方式很熟悉,但是我們有很多情況下并不能直接使用form表單方式直接提交。這時(shí)候我們就需要使用Ajax方式提交,Ajax有很多的好處,比如當(dāng)我們不需要刷新頁面獲希望進(jìn)行局部刷新的時(shí)候,我們就可以使用Ajax。下面是我的表單提交的JSP頁面,其中包含JS的詳細(xì)步驟和HTML文件:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ include file="../commons/taglibs.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>發(fā)布資訊</title> <script type="text/javascript" src="${ctx}/resources/new_js/jquery.js"></script> <script type="text/javascript" src="${ctx}/resources/js/ajaxfileupload.js"></script> <script type="text/javascript"> function save(){ var typeId = $("#type_span_info").attr("data-id"); if (typeof (typeId) == "undefined") { $("#type_p_info").show(); return; } else { $("#type_p_info").hide(); } var title = $("#title_input_info").val(); var summary = $("#summary_input_info").val(); var content = $("#content_textarea_info").val(); $.ajaxFileUpload({ url : "${ctx}/info/doUpload", secureuri : false,//是否需要安全協(xié)議 fileElementId : 'file', type : 'POST', //文件提交的方式 dataType : 'string', cache : false, //是否進(jìn)行頁面緩存 async : true, // 是否同步提交 success : function(data) { $.ajax({ url : '${ctx}/info/addInfo?fileUrl='+data, type : 'post', data:{title:title,summary:summary,content:content,typeId:typeId}, async : false, success : function(result) { if (result == 1) { $("#del_prompt_p").text("添加成功"); fnError3(); } else if (result == 2) { $("#del_prompt_p").text("添加失敗") fnError2(); } else { $("#del_prompt_p").text("系統(tǒng)錯(cuò)誤"); fnError2(); } } }); } }); } </script> </head> <body class="body_bg"> <div class="main"> <!--頁面主體 start--> <div class="main_content"> <div class="later_index clear wrap"> <div class="later_right fr"> <div class="roll_parent" id="roll_parent"> <div class="scroll_parent" id="scroll_parent"> <div class="scroll" id="scroll"></div> </div> <div class="roll_son" id="roll_son"> <div class="later_content later_content1"> <div class="release_name"> <h3> <span>發(fā)布資訊</span> </h3> </div> <div class="issue_content"> <form action="" id="form1" method="post" enctype="multipart/form-data"> <table class="issue_tab"> <tbody> <tr> <td><p><i>*</i><strong>標(biāo)題</strong></p> </td> </tr> <tr> <td><input id="title_input_info" name="title_input_info" type="text" placeholder="最多可以輸入40個(gè)字" type="text" maxlength="40"/> <!-- <span class="colse"></span> --> <p class="colse_tip"></p> <!-- <p class="colse_tip" id="title_p_info" style="display:hidden;">請選擇標(biāo)題!</p> --> </td> </tr> <tr> <td><p><i>*</i><strong>摘要</strong></p></td> </tr> <tr> <td><input name="summary_input_info" id="summary_input_info" type="text" placeholder="最多可以輸入100個(gè)字" type="text" maxlength="100" /> <p class="colse_tip"></p></td> </tr> <tr> <td><p><i>*</i><strong>內(nèi)容</strong></p> </td> </tr> <tr> <td><textarea name="content_textarea_info" id="content_textarea_info"></textarea> <p class="colse_tip"></p></td> </tr> <tr> <td><p><i>*</i><strong>選擇行業(yè)</strong></p> <p class="colse_tip" id="type_p_info" style="display:hidden;">請選擇行業(yè)!</p></td> </tr> <tr> <td> <div class="next_select select_width select_bg" id="next_select0"> <span id="type_span_info">請選擇</span> </div> <div class="select_box select_top select_width" data-id="" id="select_box0"> <ul> <li class="curr" data-id="2">化工</li> <li data-id="3">裝備制造</li> <li data-id="4">生物醫(yī)藥</li> <li data-id="5">電子信息</li> <li data-id="6">其他</li> </ul> </div> </td> </tr> <tr> <td> <input type="button" class="isue_inp_btn" value="添加圖片"/> <input type="text" id="issue_input_text" class="issue_text" /> <input type="file" id="file" name="file" class="issue_file" onchange="javaScript:validate_img(this)" /> </td> </tr> </tbody> </table> </form> </div> <div class="financial_pro_icon"> <div class="financial_pro_icon_l issue_btn1"> <a href="javaScript:save();">發(fā)布</a> </div> <div class="financial_pro_icon_r issue_btn1"> <a href="${ctx}/info/gotoInfo?index=2">取消</a> </div> </div> </div> </div> </div> </div> </div> </div> <!--頁面主體 end--> </div> </body> </html>
上面的代碼是我在項(xiàng)目實(shí)際開發(fā)的過程中所用的代碼,具體的CSS文件與JS文件我已經(jīng)刪掉了,但是不會(huì)影響具體的操作,大家使用的時(shí)候只需要把其中的class文件刪掉了就可以了。好了,我們在說一說上面的代碼。首先為大家解釋一下ctx的作用,在我們項(xiàng)目開發(fā)的過程中,我們要求必須使用絕對(duì)路徑,所有{ctx}是我們封裝好的一個(gè)東西,就是我們的服務(wù)器地址+端口號(hào)+項(xiàng)目名稱。當(dāng)我們使用的時(shí)候,只需要引用一下文件,就是上面直接使用的<%@ include file=”../commons/taglibs.jsp”%>,當(dāng)我們用的時(shí)候直接使用${ctx}就可以,大家在使用的時(shí)候就直接使用自己的本機(jī)地址端口號(hào)與項(xiàng)目名稱就可以。后面的/resources/new_js/jquery.js就是我們要使用的jqery.js文件的存放地址。
其實(shí)在上面的Ajax的操作中,我相當(dāng)于做了兩次的Ajax的提價(jià),但是在第一次提交的時(shí)候,后臺(tái)給我們返回一個(gè)參數(shù),就是我們的文件存放路徑與文件名稱,在第二次提交的時(shí)候,我們將這些參數(shù)與其他參數(shù)同時(shí)上傳到后臺(tái),并將這些參數(shù)保存到數(shù)據(jù)庫中,以便我們使用。
* 4 后臺(tái)代碼:
//文件上傳 @RequestMapping(value = "/doUpload", method = RequestMethod.POST, produces = "text/html; charset=UTF-8") @ResponseBody public String doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { List<String> fileNames = null; if (request instanceof MultipartHttpServletRequest) { // process the uploaded file logger.info("=====進(jìn)入文件類型選擇====="); fileNames = uploadAttachment(request, "file"); } String url = ""; if (fileNames.size() > 0) { for (int i = 0; i < fileNames.size(); i++) { url = url + fileNames.get(i); if(i < fileNames.size() - 1){ url = url + ","; } } } return url; } //文件上傳的工具類 public List<String> uploadAttachment(HttpServletRequest request, String type) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; List<MultipartFile> files = multipartRequest.getFiles(type); logger.info("數(shù)據(jù)長度========>>>>>>>>>>" + files.size()); Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH) + 1; String realPath = PropertiesUtil.getProperty("realPath"); System.err.println("realpath=====>>>>>" + realPath); //String savePath = request.getSession().getServletContext().getRealPath("/") + "p_image\\" + type + "\\" + year+ "\\" + month + "\\"; String savePath = "government"+ File.separator + "image"+ File.separator + year+ File.separator + month + File.separator; logger.info("保存路徑=====>" + savePath); List<String> fileNames = new ArrayList<String>(); for (MultipartFile multipartFile : files) { logger.info("--" + multipartFile.getOriginalFilename()); String fileName = multipartFile.getOriginalFilename(); String prefix = fileName.substring(fileName.lastIndexOf(".") + 1); String custName = "" + System.currentTimeMillis() + "." + prefix; if (UsedUtil.isNotNull(fileName)) { File targetFile = new File(realPath+savePath, custName); // fileName = year+"-"+month+"-"+fileName; if (!targetFile.exists()) { targetFile.mkdirs(); multipartFile.transferTo(targetFile); } try { } catch (Exception e) { e.printStackTrace(); } fileNames.add(savePath + custName); } } return fileNames; } //添加咨詢 @RequestMapping(value = "/addInfo", method = RequestMethod.POST) @ResponseBody public Integer addInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileUrl) { InfoBean bean = new InfoBean(); if(UsedUtil.isNotNull(fileUrl)){ bean.setImagePath(fileUrl); } Map<String, Object> paramMap = ControllerUtil.request2Map(request); bean.setTitle((String) paramMap.get("title")); bean.setSummary((String) paramMap.get("summary")); bean.setContent((String) paramMap.get("content")); bean.setTypeId((String)paramMap.get("typeId")); return infoService.insInfo(bean); }
在上面的代碼中我們可以看到,在文件第一次上傳的過程中,我們首先進(jìn)入到doUpload中,然后使用uploadAttachment工具類,并將文件上傳到服務(wù)器中,在上傳的過程中,我首先做了一個(gè)文件唯一名稱的操作,就是獲取當(dāng)前時(shí)間的毫秒數(shù),雖然不能絕對(duì)保證,但是到并發(fā)量小的時(shí)候可以保證不會(huì)造成文件名稱重復(fù)。然后,我將文件上傳的路徑的上傳地址寫到了.properties中,這樣的好處是當(dāng)我們想更換文件上傳的路徑時(shí),我們就可以直接修改.properties文件,而讀取.properties文件的具體方式在我的另一篇文章中講到。最后,我們在開發(fā)的過程中,文件保存一般是保存到文件服務(wù)器中,而文件服務(wù)器一般是在Linux中,而在不同的服務(wù)器中,路徑是使用斜杠還是反斜杠是不同的,所有我在這里面使用了File.separator來代替,F(xiàn)ile.separator在不同的系統(tǒng)中可以自動(dòng)生成斜杠獲反斜杠。
以上所述是小編給大家介紹的使用Ajax進(jìn)行文件與其他參數(shù)的上傳功能(java開發(fā)),希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的,在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
ASP+AJAX+ACCESS數(shù)據(jù)庫實(shí)例講解三個(gè)步驟分享
其實(shí)說起AJAX的初級(jí)應(yīng)用是非常簡單的,通俗的說就是客戶端(javascript)與服務(wù)端(asp或php等)腳本語言的數(shù)據(jù)交互2012-07-07基于Jquery.history解決ajax的前進(jìn)后退問題
本文主要給大家介紹基于Jquery.history解決ajax的前進(jìn)后退問題,涉及到j(luò)query前進(jìn)后退相關(guān)方面的知識(shí),本文內(nèi)容經(jīng)典,非常具有參考價(jià)值,特此把jquery前進(jìn)后退相關(guān)知識(shí)分享在腳本之家網(wǎng)站供大家參考2015-10-10Ajax工作原理及優(yōu)缺點(diǎn)實(shí)例解析
這篇文章主要介紹了Ajax工作原理及優(yōu)缺點(diǎn)實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09JQuery+ajax實(shí)現(xiàn)批量上傳圖片(自寫)
jquery+ajax方式實(shí)現(xiàn)單張圖片上傳的代碼是可以搜的到,實(shí)現(xiàn)批量上傳圖片的程序卻沒搜索到于是自己寫了個(gè),感興趣的朋友可以參考下2013-04-04