이 기사는 Java Background Batch 다운로드 파일에 대한 특정 코드를 공유하고 참조를 위해 ZIP 다운로드로 압축합니다. 특정 내용은 다음과 같습니다
프로젝트 요구로 인해 서버의 이미지 파일은 압축 및 포장되어 로컬 데스크탑으로 다운로드됩니다.
첫째, 프론트 엔드 JS :
함수 doquerypic () {var picsdate = $ ( "#picsdate"). val (); var pianodate = $ ( "#picdate"). val (); var picinst = $ ( "#pic_inst"). combotree ( "getValue"); var svrcode = $ ( "#pic_svr_code"). val (); var picstime = $ ( "#pic_stime"). val (); var pianotime = $ ( "#pic_etime"). val (); if (svrcode == null) {$ .messager.alert ( 'hint', "트랜잭션 쿼리 코드를 입력하십시오"); 반품; } else {$ .ajax ({type : "post", url : 'querypic.translog.action', data : {f_brno : picinst, f_sdate : picsdate, f_edate : picdate, f_svr_code : svrcode, f_stime, f_etime : inctime}, function} : if (rcdata.success) {var rows = rcdata.picinfo; var detailshtml = '<table class ='my-table 'cellpading ='0 'width = '90%'align = 'center'> <th style = 'width : 5%; center'> <input type ''swapch All </th> <th Style = 'width : 10%; 텍스트-정렬 : 중심'> 날짜 </th> <th Style = '너비 : 10%; 텍스트-정렬 : 센터'> 날짜 </th> <th style = '너비 : 10%; 텍스트-정렬 : 센터'>는 어떤 이미지 </th> <th style = 'width : 23%; 센터'> 트레이딩 '> 트레이딩'> 10%; 텍스트-정상 : 중심 '> 거래 상태 </th> <th Style ='width : 12%; 텍스트-정렬 : 센터 '> 장치 번호 </th> <th style ='width : 10%; 텍스트-정렬 : 센터 '> 트레이딩 코드 </th> <th Style ='width : 10%; 텍스트-정렬 : 센터 '> 텍스트> 텍스트 = 중심; 시간 </th> </tr> </thead> <tbody> "; for (var i = 0; i <rows.length; i ++) {detailhhtml = detailhtml +"<tr> <td elign = 'center'> <입력 유형 = 'checkbox'name = 'pictureId'value = '' + rows [i] .f_date + rows [i] .f_ic _. /> </td> <td> " + 행 [i] .f_date +"</td> <td> " + 행 [i] .ishasimg +"</td> <td> " + 행 [i] .f_dev_id + "</td> <td>" + 행 [i] .f_svr_code + "</td> <td>" + 행 [i] .f_svr_code + "</td> <td>" + rows [i] .f_brno + "<td>" + row [i]. "</td> </tr>"; }); }}}위의 코드는 관련 데이터를 쿼리 한 후 인터페이스에 표시 된 다음 고객의 요구에 따라 다운로드 및 저장할 데이터를 선택할 수 있습니다.
확인란 첨부 모든 JS 코드를 선택하십시오
// CheckBox ALL/CANCEL SELECT/CANCEL 모든 var ischeckall = false; function swapcheck () {if (iScheckall) {$ ( "input [type = 'checkbox']"). 각 (function () {this.checked = false;}); ischeckall = false; } else {$ ( "input [type = 'checkbox']"). 각 (function () {this.checked = true;}); ischeckall = true; }} 다음 코드는 배경 상호 작용에 사용됩니다. 파일을 다운로드하면 AJAX를 사용하여 데이터를 보내지 마십시오. 나는 전에 그것을했고 다운로드 할 수 없었습니다. 나는 하루 종일 그것을 발견했다. 주석 부분은 Ajax 코드입니다. 참조로 볼 수 있습니다.
함수 downloadPic () {var arr = new Array (); var picids = document.getElementsByName ( "pictureId"); for (i = 0; i <picids.length; i ++) {if (picids [i] .checked) {arr.push (picids [i] .value); }} if (Ar 반품; } else {$ ( '#formpic'). attr ( 'action', 'downloadpic.translog.action'); $ ( "#formpic"). form ( '제출', {onsubmit : function () {}, success : function (data) {$ .messager.alert ( 'hint', 'image download', 'info');}}); /***$. ajax ({type : "post", url : 'downloadpic.translog.action', data : {picturelist : json.stringify (arr)}, success : function (rcdata) {if (rcdata.success) {$ .messager.show ({title : '}); $ .messager.alert ( 'hint', rcdata.errmsg)} {alert (alert!}); */}} 다음은 배경 상호 작용입니다. 우선 컨트롤러 제어 계층입니다.
/** * 이미지 배치 다운로드 * @param request * @param response * @return * @throws ioexception */public void downloadPic (httpservletrequest request, httpservletResponse 응답) ioexception {// map <string, object> params = getParameters (request); 문자열 [] pictureIds = request.getParametErvalues ( "pictureId"); 인증 au = getAuthentication (요청); service.downloadpic (PictureIds, au, 요청, 응답); 반품 ; } 서비스 계층 :
public void downloadpic (string [] params, Authentication Au, httpservletrequest request, httpservletResponse 응답)은 ioexception {// 압축 파일의 초기 설정 = system.getProperty ( "ics.webapp.root"); // 이것은 서버 경로, request.getrestion (). 사용 된 문자열 filezip = au.getusername ()+"-"+au.getAttribute ( "f_brno")+"pictures.zip"; String FilePath = path + "//" + fileZip; // 그런 다음 zip 파일을 생성하는 데 사용됩니다. // filepatharr는 전경에서 전송 된 정보를 기반으로 데이터베이스 쿼리를 통해 얻은 PDF 파일 경로 세트입니다 (특별히 접미사) 목록 <map <string, object >> filenamearr = new arrayList <string, object >> (); // jsonarray jsons = jsonarray.fromobject (params.get ( "picturelist")); /***list <string> pictureIds = new ArrayList <string> (); for (object obj : jsons) {pictureIds.add (obj.toString ()); } */ for (int i = 0; i <params.length; i ++) {map <string, object> spemap = new Hashmap <string, object> (); spemap.put ( "f_date", params [i] .substring (0, 8)); spemap.put ( "f_ics_batch", params [i] .substring (8)); list <map <string, object >> reclists = dao.queryloginfo (spemap); for (int j = 0; j <reccists.size (); j ++) {filenamearr.add (recists.get (j)); }} // 파일 주소와 파일 이름을 포함하여 압축 해야하는 파일 // string [] pathtytyt = { "d : //13.jpg", "d : //1212.jpg"}; // 생성 할 압축 된 파일 주소와 파일 이름 // String despath = "d : //downloads//new.zip"; 파일 zipfile = 새 파일 (filepath); ZipOutputStream ZipStream = null; FileInputStream ZipSource = null; bufferedInputStream bufferstream = null; 시도 {// 최종 압축 패키지의 출력 스트림을 구성 ZIPSTREAM = NEW ZIPOUTPUTSTREAM (new FileOutputStream (ZipFile)); for (int i = 0; i <filenamearr.size (); i ++) {file file = 새 파일 ((string) filenamearr.get (i) .get ( "f_filename"); // 파일 = 새 파일 (pathtytyt [i]); // 입력 스트림으로 압축 해야하는 파일을 형식화 zipsource = new FileInputStream (파일); // 압축 항목은 특정 독립 파일이 아니지만 index //와 마찬가지로 entries라는 압축 패키지 파일 목록에 항목을 나열합니다. 여기서 나는 단일 파일 인식에 사용됩니다. Zipentry Zipentry = new Zipentry (i+file.getName ()); // 압축 된 항목의 위치를 찾아서 압축 패키지 ZIPSTREAM.PETNEXTENTRY (Zipentry)에 파일을 쓰기 시작합니다. // 입력 bufferstream = new bufferedInputStream (Zipsource, 1024 * 10); int read = 0; // 읽기 및 쓰기 버퍼 바이트 생성 [] buf = new Byte [1024 * 10]; while ((read = bufferstream.read (buf, 0, 1024 * 10))! = -1) {zipstream.write (buf, 0, read); }}} catch (예외 e) {e.printstacktrace (); } 마침내 {// 스트림을 닫으십시오. {if (null! = bufferstream) bufferstream.close (); if (null! = zipstream) zipstream.close (); if (null! = zipsource) zipsource.close (); } catch (ioexception e) {e.printstacktrace (); }} /*** 프론트 엔드 브라우저에 스트림 파일을 쓰기 ServletOutStream os = response.getoutPutStream (); Response.setContentType ( "Application/X-Octet-Stream"); response.setContentLength ((int) zipfile.length ()); response.addheader ( "content-disposition", "첨부 파일; filename =" + urlencoder.encode (filezip, "utf-8")); bufferedInputStream bis = null; BufferedOutputStream BOS = NULL; try {bis = new bufferedInputStream (new FileInputStream (filepath)); BOS = 새로운 BufferedOutputStream (OS); 바이트 [] buff = 새로운 바이트 [2048]; int bytesread; while (-1! = (bytesread = bis.read (buff, 0, buff.length))) {bos.write (buff, 0, bytesread); } os.flush (); os.close (); } catch (ioexception e) {Throw e; } 마침내 {if (bis! = null) bis.close (); if (bos! = null) bos.close (); 파일 obj = 새 파일 (filepath); if (obj.exists ()) {obj.delete (); // 서버에서 로컬로 생성 된 임시 압축 파일 삭제}}*// 브라우저 다운로드 // 브라우저 프록시 정보 최종 문자열 userAgent = request.getheader ( "user-agent"); // 브라우저 프록시를 판단하고 브라우저에 각각 응답하는 인코딩 형식을 string finalfilename = null; if (stringUtils.contains (userAgent, "msie") || stringUtils.contains (userAgent, "trident")) {// 브라우저 finalFilename = urlencoder.encode (filezip, "utf-8"); System.out.println ( "즉, 브라우저"); } else if (stringUtils.contains (userAgent, "mozilla")) {// google, firefox 브라우저 FinalFilename = urlencoder.encode (filezip, "utf-8"); } else {finalFilename = urlencoder.encode (filezip, "utf-8"); // 다른 브라우저} response.setContentType ( "application/x-octet-stream"); // 파일을 직접 열지 말라고 브라우저에 알려주십시오. 브라우저는 기본적으로 응답을 엽니 다 .setheader ( "Content-Disposition", "attachment; filename =" +finalFilename); // 다운로드 파일의 이름 ServletOutStream ServletOutStream = response.getOutputStream (); DataOutputStream temps = 새로운 DataOutputStream (ServletOutputStream); datainputStream in = new DatainputStream (new FileInputStream (filepath)); // 브라우저 다운로드 파일 바이트 [] b = 새로운 바이트 [2048]; file reportzip = 새 파일 (filepath); // 그런 다음 임시 압축 파일을 삭제하는 데 사용됩니다 {while ((in.read (b))! = -1) {temps.write (b); } temps.flush (); } catch (예외 e) {e.printstacktrace (); optlogsvc.savelog (au.getusername (), au.getattribute ( "f_brno"), au.getAttribute ( "f_lstip"), toptlogservice.type_mr, "", au.getusername ()+"batch download"+filezip+"실패!"); } 마침내 {if (temps! = null) temps.close (); if (in! = null) in.close (); if (reportzip! = null) reportzip.delete (); // 서버 ServletoutPutStream.close ()에 의해 로컬로 생성 된 임시 압축 파일을 삭제합니다. } /***if (picinfollist.size ()> 0) {rc.put ( "success", true); rc.put ( "Picinfo", PicinFollist); optlogsvc.savelog (au.getusername (), au.getattribute ( "f_brno"), au.getAttribute ( "f_lstip"), toptlogservice.type_mr, "", au.getusername ()+"Query Download"+params.get ( ");"); } else {rc.put ( "success", false); rc.put ( "errmsg", "테스트 정보"); optlogsvc.savelog (au.getusername (), au.getattribute ( "f_brno"), au.getAttribute ( "f_lstip"), toptlogservice.type_mr, "", au.getusername ()+"Query Download"+"+"+"get!"); }*/ optlogsvc.savelog (au.getusername (), au.getAttribute ( "f_brno"), au.getAttribute ( "f_lstip"), toptlogservice.type_mr, ", au.getusername ()+"batch download "+"success! "); 반품 ; }JSON 배열 변환 형식에는 문제가 있습니다. 프론트 엔드 JSON에서 보낸 JSON이 JSON.Stringify에 의해 형식화되면 배경으로 갈 때 이러한 방식으로 구문 분석해야합니다.
내 레이아웃 기술이 좋지 않으므로 살펴 보겠습니다. 브라우저가 온라인으로 복사되었다고 판단했지만 쓸모없고 중국어를 인식 할 수 없다는 것을 알았습니다. 결국, 나는 파일 이름으로 영어를 타협하고 여전히 사용했습니다. 중국어가 달린 코드를 만나면 바이두에서 다시 검색 할 수 있습니다. 다른 사람들은 비슷한 기사를 썼지 만 연구 할 에너지는 없습니다.
이것은 서버에 존재하는 파일을 압축하는 방법입니다. 또한 네트워크 사진을 얻고 압축 및 다운로드하기 전에 Baidu 관련 기사를 보았습니다. 흥미 롭습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.