SpringMVC+Ajax實(shí)現(xiàn)文件批量上傳和下載功能實(shí)例代碼
今天做了文件的上傳下載,小小總結(jié)一下,基本的web項(xiàng)目建立及SpringMVC框架搭建此處不詳細(xì)寫出來了。
上傳form:
<form id="uploadfiles" enctype="multipart/form-data"> <input type="file" multiple="multiple" id="file_upload" name="file_upload" /> <input type="button" value="上傳" onclick="upload()" /> </form>
上傳Ajax:
<script type="text/javascript"> /* * 上傳文件 */ function upload(){ var formData = new FormData($( "#uploadfiles" )[0]); $.ajax({ type: "post", url: "./path/upload", dataType: "json", data: formData, /** *必須false才會(huì)自動(dòng)加上正確的Content-Type */ contentType : false, /** * 必須false才會(huì)避開jQuery對(duì) formdata 的默認(rèn)處理 * XMLHttpRequest會(huì)對(duì) formdata 進(jìn)行正確的處理 */ processData : false, success: function(data){//從后端返回?cái)?shù)據(jù)進(jìn)行處理 if(data){ alert("上傳成功!"); }else{ alert("上傳失??!"); } }, error: function(err) {//提交出錯(cuò) $("#msg").html(JSON.stringify(err));//打出響應(yīng)信息 alert("服務(wù)器無響應(yīng)"); } }); } </script>
spring.xml配置加上:
<!-- 配置文件上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默認(rèn)編碼 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 內(nèi)存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> controller: /* * 上傳多個(gè)文件 */ @RequestMapping(value = "/upload", produces = "application/json;charset=UTF-8") public @ResponseBody boolean uploadFiles(@RequestParam("file_upload") MultipartFile [] files) { boolean result = false; String realPath; for(int i=0;i<files.length;i++){ if (!files[i].isEmpty()) { String uniqueName=files[i].getOriginalFilename();//得到文件名 realPath="E:"+File.separator+uniqueName;//文件上傳的路徑這里為E盤 files[i].transferTo(new File(realPath)); // 轉(zhuǎn)存文件 result = true; } catch (Exception e) { e.printStackTrace(); } } } return result; }
下載的jsp頁面代碼根據(jù)需求不同自己設(shè)計(jì),這里給出controller代碼:
/* * 下載多個(gè)文件 */ @RequestMapping(value = "/download") public void downloadFiles(HttpServletResponse response) { String str= request.getParameter("rows");//下載文件信息,包括文件名、存儲(chǔ)路徑等 JSONArray path=(JSONArray) JSONArray.parse(request.getParameter("rows")); Path paths[]=new Path[path.size()]; paths = JSONArray.parseArray(str, Path.class).toArray(paths); String uri = "d:"+ File.separator + "mldn.zip";//臨時(shí)文件存儲(chǔ)路徑 File zipFile = new File(uri) ; // 定義壓縮文件名稱 ZipOutputStream zipOut = null;// 聲明壓縮流對(duì)象 InputStream input = null; //將要壓縮的文件加入到壓縮輸出流中 try { zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } for(int i = 0;i<paths.length;i++){ File file = new File(paths[i].getUri()+File.separator+paths[i].getFilename()); try { input = new FileInputStream(file) ;// 定義文件的輸入流 zipOut.putNextEntry(new ZipEntry(file.getName())) ; // 設(shè)置ZipEntry對(duì)象 } catch (Exception e) { e.printStackTrace(); } } //將文件寫入到壓縮文件中 int temp = 0 ; try { while((temp=input.read())!=-1){ // 讀取內(nèi)容 zipOut.write(temp) ; // 寫到壓縮文件中 } } catch (IOException e) { e.printStackTrace(); }finally{ try { input.close() ; zipOut.close() ; } catch (IOException e) { e.printStackTrace(); } } try { // 以流的形式下載文件。 BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFile)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/x-msdownload;"); response.setHeader("Content-Disposition", "attachment;filename=" + zipFile.getName()); toClient.write(buffer); toClient.flush(); toClient.close(); zipFile.delete(); //將生成的服務(wù)器端文件刪除 } catch (IOException ex) { ex.printStackTrace(); } }
將多個(gè)文件打成一個(gè)壓縮包下載,然后將生成的臨時(shí)壓縮文件刪除。
下載頁面如果用Ajax提交請(qǐng)求的話要注意:ajax函數(shù)的返回類型只有xml、text、json、html等類型,沒有“流”類型,所以我們要實(shí)現(xiàn)ajax下載,不能夠使用相應(yīng)的ajax函數(shù)進(jìn)行文件下載。但可以用js生成一個(gè)form,用這個(gè)form提交參數(shù),并返回“流”類型的數(shù)據(jù)。
例子:
function download(){ var form=$("<form>");//定義一個(gè)form表單 form.attr("style","display:none"); form.attr("target",""); form.attr("method","post"); form.attr("action","./path/download");//請(qǐng)求url var input1=$("<input>"); input1.attr("type","hidden"); input1.attr("name","rows");//設(shè)置屬性的名字 input1.attr("value",“test”);//設(shè)置屬性的值 $("body").append(form);//將表單放置在web中 form.append(input1); form.submit();//表單提交 }
總結(jié)
以上所述是小編給大家介紹的SpringMVC+Ajax實(shí)現(xiàn)文件批量上傳和下載功能實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- ajax post下載flask文件流以及中文文件名問題
- javascript寫一個(gè)ajax自動(dòng)攔截并下載數(shù)據(jù)代碼實(shí)例
- Ajax請(qǐng)求二進(jìn)制流進(jìn)行處理(ajax異步下載文件)的簡(jiǎn)單方法
- 利用 FormData 對(duì)象和 Spring MVC 配合實(shí)現(xiàn)Ajax文件下載功能
- 基于Blod的ajax進(jìn)度條下載實(shí)現(xiàn)示例代碼
- PHP中ajax無刷新上傳圖片與圖片下載功能
- 使用Ajax生成的Excel文件并下載的實(shí)例
- jQuery的ajax下載blob文件
- jQuery+Ajax+PHP彈出層異步登錄效果(附源碼下載)
- PHP+Ajax實(shí)現(xiàn)無刷新分頁實(shí)例詳解(附demo源碼下載)
- 前端ajax請(qǐng)求+后端java實(shí)現(xiàn)的下載zip壓縮包功能示例
相關(guān)文章
仿google搜索提示 SuggestFramework的使用
使用幫助(英文版翻譯而來,可能有錯(cuò)誤,請(qǐng)大家仔細(xì)核對(duì),也希望對(duì)新手理解能有所幫助)2008-09-09探討.get .post .ajax ztree 還有后臺(tái)servlet傳遞數(shù)據(jù)的相關(guān)知識(shí)
這篇文章主要介紹了探討.get .post .ajax ztree 還有后臺(tái)servlet傳遞數(shù)據(jù)的相關(guān)知識(shí),需要的朋友可以參考下2015-12-12PHP匹配連續(xù)的數(shù)字或字母的正則表達(dá)式
PHP匹配連續(xù)的數(shù)字或字母的正則表達(dá)式,需要的朋友可以參考下。2011-05-05強(qiáng)烈推薦 - Ajax 技術(shù)資源中心
強(qiáng)烈推薦 - Ajax 技術(shù)資源中心...2007-05-05history保存列表頁ajax請(qǐng)求的狀態(tài)使用示例詳解
這篇文章主要為大家介紹了history保存列表頁ajax請(qǐng)求的狀態(tài)使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12ASP.NET與Ajax的實(shí)現(xiàn)方式小總結(jié)
Ajax 應(yīng)該不是一項(xiàng)技術(shù),是一種思想而已,跟 ASP.NET 以及其它 Web 開發(fā)語言沒有什么太大關(guān)系,這里只是談?wù)?ASP.NET 中目前使用的 Ajax 技術(shù)以及其它一些實(shí)現(xiàn) Ajax 的優(yōu)秀框架。感興趣的朋友跟著小編一起學(xué)習(xí)asp.net與ajax的實(shí)現(xiàn)方式2015-09-09AJAX+JSP實(shí)現(xiàn)讀取XML內(nèi)容并按排列顯示輸出的方法示例
這篇文章主要介紹了AJAX+JSP實(shí)現(xiàn)讀取XML內(nèi)容并按排列顯示輸出的方法,結(jié)合實(shí)例形式分析了ajax與后臺(tái)jsp頁面交互實(shí)現(xiàn)xml內(nèi)容的排列輸出相關(guān)操作技巧,需要的朋友可以參考下2018-06-06AJAX實(shí)現(xiàn)JSON與XML數(shù)據(jù)交換方法詳解
這篇文章主要介紹了AJAX實(shí)現(xiàn)JSON與XML數(shù)據(jù)交換方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01herf=#導(dǎo)致Ajax請(qǐng)求時(shí)沒有向后臺(tái)發(fā)送數(shù)據(jù)
當(dāng)點(diǎn)擊重命名進(jìn)行Ajax請(qǐng)求時(shí),并沒有向后臺(tái)發(fā)送數(shù)據(jù)而是直接跳轉(zhuǎn)到了首頁,后來發(fā)現(xiàn)是這個(gè)herf=#惹的禍2014-05-05