2018-07-16 11:49:52 1267瀏覽
在目前大多數(shù)Java開發(fā)程序項目中經(jīng)常會使用到文件上傳及下載的功能,扣丁學(xué)堂Java培訓(xùn)為大家分享了JavaWeb多文件上傳及zip打包下載的具體代碼及多文件上傳及批量打包下載功能,包括前臺及后臺部分,下面我們一起來看一下吧。注意一點:無法通過頁面的無刷新ajax請求,直接發(fā)下載、上傳請求。上傳和下載,均需要在整頁請求的基礎(chǔ)上實現(xiàn)。項目中一般通過構(gòu)建form表單形式實現(xiàn)這一功能。
<formid="uploadForm"method="post"enctype="multipart/form-data"> <inputtype="file"hiddenname="fileImage"multiple/> <ahref="javascript:void(0);"rel="externalnofollow"rel="externalnofollow"id="fileSubmit"onclick="uploadFileMulti()">上傳資料</a> </form>
varformData=newFormData($("#uploadForm")[0]); formData.append("foldName","datumList");//設(shè)置父級文件夾名稱 ? formData.append("oderCode",selfOrderCode); formData.append("datumType",datumType); $.ajax({ type:"POST", data:formData, url:"order/datumList/batchInsertDatumLists", contentType:false, processData:false, success:function(result){ if(result.success){ //清空框文件內(nèi)容 $("#fileImage").val(""); varobj=document.getElementById('fileImage'); obj.outerHTML=obj.outerHTML; refreshDatumList(); showSuccessToast(result.message); }else{ showWarningToast(result.message); } }, error:function(){ showErrorToast('請求失?。?) } });
MultipartHttpServletRequestmRequest=(MultipartHttpServletRequest)request; List<MultipartFile>files=mRequest.getFiles("fileImage");
<formid="uploadForm"method="post"enctype="multipart/form-data"> <divclass="product-dl"> <inputtype="hidden"name="orderCode"/> <inputtype="hidden"name="datumType"/> <ahref="javascript:void(0);"rel="externalnofollow"rel="externalnofollow"class="btn"onclick="batchDatumListDownLoad()">批量下載</a> </div> </form> JS部分 //批量下載 functionbatchDatumListDownLoad(){ varparam={}; param.datumType=$("#datumTypeQ").val(); if(param.datumType==-1){ param.datumType=null;//查詢所有 } param.orderCode=selfOrderCode; $("#uploadForminput[name=orderCode]").val(param.orderCode); $("#uploadForminput[name=datumType]").val(param.datumType); varform=$("#uploadForm")[0]; form.action="order/datumList/batchDownLoadDatumList"; form.method="post"; form.submit();//表單提交 } 后臺部分 publicvoidbatchDownLoadDatumList(DatumListVodatumListVo,HttpServletResponseresponse){ try{ //查詢文件列表 List<DatumListVo>voList=datumListService.queryDatumLists(datumListVo); //壓縮文件 List<File>files=newArrayList<>(); for(DatumListVovo:voList){ Filefile=newFile(vo.getDatumUrl()); files.add(file); } StringfileName=datumListVo.getOrderCode()+"_"+datumListVo.getDatumType()+".zip"; //在服務(wù)器端創(chuàng)建打包下載的臨時文件 StringglobalUploadPath=""; StringosName=System.getProperty("os.name"); if(osName.toLowerCase().indexOf("windows")>=0){ globalUploadPath=GlobalKeys.getString(GlobalKeys.WINDOWS_UPLOAD_PATH); }elseif(osName.toLowerCase().indexOf("linux")>=0||osName.toLowerCase().indexOf("mac")>=0){ globalUploadPath=GlobalKeys.getString(GlobalKeys.LINUX_UPLOAD_PATH); } StringoutFilePath=globalUploadPath+File.separator+fileName; Filefile=newFile(outFilePath); //文件輸出流 FileOutputStreamoutStream=newFileOutputStream(file); //壓縮流 ZipOutputStreamtoClient=newZipOutputStream(outStream); //設(shè)置壓縮文件內(nèi)的字符編碼,不然會變成亂碼 toClient.setEncoding("GBK"); ZipUtil.zipFile(files,toClient); toClient.close(); outStream.close(); ZipUtil.downloadZip(file,response); }catch(Exceptione){ e.printStackTrace(); } } 其中ZipUtil.java /** *壓縮文件列表中的文件 * *@paramfiles *@paramoutputStream *@throwsIOException */ publicstaticvoidzipFile(Listfiles,ZipOutputStreamoutputStream)throwsIOException,ServletException{ try{ intsize=files.size(); //壓縮列表中的文件 for(inti=0;i<size;i++){ Filefile=(File)files.get(i); try{ zipFile(file,outputStream); }catch(Exceptione){ continue; } } }catch(Exceptione){ throwe; } } /** *將文件寫入到zip文件中 * *@paraminputFile *@paramoutputstream *@throwsException */ publicstaticvoidzipFile(FileinputFile,ZipOutputStreamoutputstream)throwsIOException,ServletException{ try{ if(inputFile.exists()){ if(inputFile.isFile()){ FileInputStreaminStream=newFileInputStream(inputFile); BufferedInputStreambInStream=newBufferedInputStream(inStream); ZipEntryentry=newZipEntry(inputFile.getName()); outputstream.putNextEntry(entry); finalintMAX_BYTE=10*1024*1024;//最大的流為10M longstreamTotal=0;//接受流的容量 intstreamNum=0;//流需要分開的數(shù)量 intleaveByte=0;//文件剩下的字符數(shù) byte[]inOutbyte;//byte數(shù)組接受文件的數(shù)據(jù) streamTotal=bInStream.available();//通過available方法取得流的最大字符數(shù) streamNum=(int)Math.floor(streamTotal/MAX_BYTE);//取得流文件需要分開的數(shù)量 leaveByte=(int)streamTotal%MAX_BYTE;//分開文件之后,剩余的數(shù)量 if(streamNum>0){ for(intj=0;j<streamNum;++j){ inOutbyte=newbyte[MAX_BYTE]; //讀入流,保存在byte數(shù)組 bInStream.read(inOutbyte,0,MAX_BYTE); outputstream.write(inOutbyte,0,MAX_BYTE);//寫出流 } } //寫出剩下的流數(shù)據(jù) inOutbyte=newbyte[leaveByte]; bInStream.read(inOutbyte,0,leaveByte); outputstream.write(inOutbyte); outputstream.closeEntry();//ClosesthecurrentZIPentryandpositionsthestreamforwritingthenextentry bInStream.close();//關(guān)閉 inStream.close(); } }else{ thrownewServletException("文件不存在!"); } }catch(IOExceptione){ throwe; } } /** *下載打包的文件 * *@paramfile *@paramresponse */ publicstaticvoiddownloadZip(Filefile,HttpServletResponseresponse){ try{ //以流的形式下載文件。 BufferedInputStreamfis=newBufferedInputStream(newFileInputStream(file.getPath())); byte[]buffer=newbyte[fis.available()]; fis.read(buffer); fis.close(); //清空response response.reset(); OutputStreamtoClient=newBufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename="+file.getName()); toClient.write(buffer); toClient.flush(); toClient.close(); file.delete();//將生成的服務(wù)器端文件刪除 }catch(IOExceptionex){ ex.printStackTrace(); } }
以上就是關(guān)于Java開發(fā)之JavaWeb實現(xiàn)多文件上傳及zip打包下載的全部內(nèi)容,最后想要了解更多內(nèi)容的小伙伴可以登錄扣丁學(xué)堂官網(wǎng)咨詢??鄱W(xué)堂不僅有專業(yè)的老師和與時俱進(jìn)的課程體系,還有大量的Java視頻教程供學(xué)員觀看學(xué)習(xí),想要快速學(xué)習(xí)Java開發(fā)技術(shù)的小伙伴快快行動吧。
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>