2018-07-16 11:49:52 444浏览
在目前大多数Java开发程序项目中经常会使用到文件上传及下载的功能,扣丁学堂Java培训为大家分享了JavaWeb多文件上传及zip打包下载的具体代码及多文件上传及批量打包下载功能,包括前台及后台部分,下面我们一起来看一下吧。注意一点:无法通过页面的无刷新ajax请求,直接发下载、上传请求。上传和下载,均需要在整页请求的基础上实现。项目中一般通过构建form表单形式实现这一功能。
<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");//设置父级文件夹名称 ? 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){ //清空框文件内容 $("#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"; //在服务器端创建打包下载的临时文件 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); //设置压缩文件内的字符编码,不然会变成乱码 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;//流需要分开的数量 intleaveByte=0;//文件剩下的字符数 byte[]inOutbyte;//byte数组接受文件的数据 streamTotal=bInStream.available();//通过available方法取得流的最大字符数 streamNum=(int)Math.floor(streamTotal/MAX_BYTE);//取得流文件需要分开的数量 leaveByte=(int)streamTotal%MAX_BYTE;//分开文件之后,剩余的数量 if(streamNum>0){ for(intj=0;j<streamNum;++j){ inOutbyte=newbyte[MAX_BYTE]; //读入流,保存在byte数组 bInStream.read(inOutbyte,0,MAX_BYTE); outputstream.write(inOutbyte,0,MAX_BYTE);//写出流 } } //写出剩下的流数据 inOutbyte=newbyte[leaveByte]; bInStream.read(inOutbyte,0,leaveByte); outputstream.write(inOutbyte); outputstream.closeEntry();//ClosesthecurrentZIPentryandpositionsthestreamforwritingthenextentry bInStream.close();//关闭 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();//将生成的服务器端文件删除 }catch(IOExceptionex){ ex.printStackTrace(); } }
以上就是关于Java开发之JavaWeb实现多文件上传及zip打包下载的全部内容,最后想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。扣丁学堂不仅有专业的老师和与时俱进的课程体系,还有大量的Java视频教程供学员观看学习,想要快速学习Java开发技术的小伙伴快快行动吧。
【关注微信公众号获取更多学习资料】