이 기사에서는 Javaweb 멀티 파일 업로드 및 ZIP 포장 및 참조 다운로드의 특정 코드를 공유합니다. 특정 내용은 다음과 같습니다
파일 업로드 및 다운로드 기능은 종종 프로젝트에 사용됩니다. 이 기사는 Javaweb 환경의 장면, 멀티 파일 업로드 및 배치 포장 및 프론트 데스크 및 백엔드 부품을 포함한 다운로드 기능을 요약합니다.
우선, 분명히하겠습니다.
페이지를 새로 고침 할 수 없으며 다운로드 및 업로드 요청을 직접 전송할 수 있습니다. 전체 페이지 요청에 따라 업로드 및 다운로드를 구현해야합니다. 이 기능은 일반적으로 프로젝트에서 양식 양식을 작성하여 달성됩니다.
1. 여러 파일을 업로드하십시오
프로젝트 요구 사항은 다중 이미지 업로드 기능을 실현하는 것입니다. 인터넷에서 발견 된 많은 플러그인 방법을 참조한 후 원래 jQuery 업로드 솔루션을 선택하기로 결정했습니다. 아래 단계를 따라 특정 코드를 게시하십시오.
1. HTML 부품 (JS로 빌드 할 수 없음)
<form id = "uploadform"method = "post"encType = "multipart/form-data"> <input type = "file"hidden name = "fileImage"multip/> <a href = "javaScript : void (0); rel = "외부 nofollow"rel = "외부 nofollow"id = "filesubmit"onclick = "uploadfilemulti ()"> 업로드 정보 </a> </form>
몇 가지 설명이 있습니다.
1. ENCTYPE = "multipart/form-data"형태
2. 예에서는 태그를 사용하여 제출을 작성하십시오
2. JS 부분
var formdata = new FormData ($ ( "#uploadform") [0]); formData.Append ( "FoldName", "DatumList"); // 부모 폴더 이름 FormData.append ( "OderCode", DencorderCode); FormData.Append ( "DatumType", DatumType); $. Ajax ({type : "post", data : formdata, url : "Order/Datumlist/BatchinsertDatumlists", contenttype : false, success, success, success, success, contement, contenttype " (rest. }, error : function () {ShowerRortoast ( '요청 실패!')}); 위에는 몇 가지 설명이 있습니다.
1. var formdata = new FormData ($ ( "#uploadform") [0]);
2. FormData.Append를 사용하십시오 ( "OderCode", DencorderCode); 다른 매개 변수를 추가합니다
Java 백엔드
multiparthttpservletrequest mrequest = (multiparthttpservletrequest) request; list <멀티 파트 파일> 파일 = mrequest.getfiles ( "fileImage");
위에는 몇 가지 설명이 있습니다.
1. 파일 태그의 이름에 해당하는 multiparthttpservletrequest를 가져옵니다.
2. 파일의 배치 다운로드
이 프로젝트에서 요구 사항은 파일의 배치를 배치하는 것입니다. zip을 사용하여 서버에서 파일을 압축 한 다음 파일을 클라이언트로 다운로드하십시오.
온라인 쿼리의 경우 Java의 자체 파일 출력 클래스를 사용하면 압축 파일에서 파일 이름 문제를 해결할 수 없습니다. 해결책 : Ant.jar 패키지를 사용하십시오. 압축 파일을 만들 때 파일의 인코딩 형식을 설정할 수 있으며 파일 이름의 문제가 해결됩니다.
HTML 부품 (JS로 빌드 할 수 없음)
<form id = "uploadform"method = "post"enctipe = "multipart/form-data"> <div> <입력 유형 = "hidden"name = "ordercode"/> <입력 유형 = "hidden"name = "datumtype"/> <a href = "javascript : void (0); rel = "외부 nofollow"rel = "외부 nofollow"onclick = "batchdatumlistdownload ()"> batchdown </a> </div> </form>
JS 부분
// 배치 다운로드 기능 BatchDatumListDownload () {var param = {}; param.datumtype = $ ( "#datumtypeq"). val (); if (param.datumtype == -1) {param.datumtype = null; // query all} param.orderCode = 독자 코드; $ ( "#uploadform input [name = ordercode]"). val (param.orderCode); $ ( "#uploadform input [name = datumtype]"). val (param.datumtype); var form = $ ( "#uploadform") [0]; form.action = "Order/Datumlist/BatchdownloadDatumlist"; form.method = "post"; form.submit (); // 양식 제출}백엔드 부분
public void batchdownloaddatumlist (datumlistvo datumlistvo, httpservletresponse 응답) {try {// 쿼리 파일 목록 <datumlistvo> volist = datumlistervice.querydatumlists (datumlistvo); // 파일 목록 <file> files = new ArrayList <> (); for (datumlistvo : volist) {file file = new File (vo.getDatumurl ()); files.add (파일); } 문자열 filename = datumListVo.getOrderCode () + "_" + DatumListVo.getDatumType () + ".zip"; // 서버 측면에서 패키지 다운로드에 대한 임시 파일 생성 globalUploadPath = ""; String OsName = System.GetProperty ( "OS.Name"); if (osname.tolowercase (). indexof ( "wind } else if (osname.tolowercase (). indexof ( "linux")> = 0 || osname.tolowercase (). indexof ( "mac")> = 0) {globaluploadpath = globalKeys.getString (globalKeys.linux_upload_path); } String outFilePath = globalUploadPath + file.separator + filename; 파일 = 새 파일 (OutfilePath); // 파일 출력 스트림 파일 OutputStream Outstream = 새 FileOutputStream (파일); // 스트림 ZipOutputStream toClient = 새로운 ZipOutputStream (아웃스트림); // 압축 파일에서 인코딩을 설정하면 Client.setencoding ( "gbk")까지 갈 수 있습니다. ziputil.zipfile (파일, toclient); toclient.close (); Outstream.close (); Ziputil.DownloadZip (파일, 응답); } catch (예외 e) {e.printstacktrace (); }}그중 Ziputil.java
/** * 압축 파일 목록의 파일 * * @param 파일 * @param outputStream * @Throws ioException */public static void ZipFile (목록 파일, ZipOutputStream outStream)은 ioException, servLeteXception {try {int size = files.size (); // (int i = 0; i <size; i ++) {file file = (파일) files.get (i); try {zipfile (file, outputstream); } catch (예외 e) {계속; }}} catch (예외 e) {Throw e; }}/** * 파일을 zip 파일 * * @param inputfile * @param outputStream * @throws 예외 */public static void zipfile (ZipOutputStream outStream) IoException, servleTeXception {if (inputfile.exists ()) {intinpile. (inputfile.) 새 fileInputStream (inputFile); bufferedInputStream binstream = 새로운 bufferedInputStream (Instream); zipentry entry = new Zipentry (inputfile.getName ()); outputStream.putNextEntry (Entry); 최종 int max_byte = 10 * 1024 * 1024; // 최대 스트림은 10m 길이의 스트림 텔 로탈 = 0입니다. // 스트림 수락의 용량 int streamnum = 0; // 분리 해야하는 스트림 수 int LeaveByte = 0; // 파일 바이트에 남은 문자 수 [] inoustByte; // 바이트 배열은 파일의 데이터를 허용합니다. streamTotal = binstream.available (); // 스트림의 최대 문자 수는 사용 가능한 방법을 통해 얻습니다. StreamNum = (int) math.floor (streamTotal /max_byte); // 스트림 파일을 얻기 위해 분리해야 할 문자 수는 leaSByte = (int) streamTotal % max_byte; // 파일을 분할 후, 나머지 번호 if (streamnum> 0) {for (int j = 0; j <streamnum; ++ j) {inoutbyte = new Byte [max_byte]; // 스트림에서 읽고 바이트 배열 BINSTREAM.READ (inOUTBYTE, 0, MAX_BYTE)에 저장; outputStream.write (InoutByte, 0, max_byte); // 스트림을 쓰기}} // 나머지 스트림 데이터를 쓰기 inoutByte = new Byte [LeaveByte]; binstream.read (Inoutbyte, 0, LeaveByte); outputStream.write (inoutbyte); outputstream.closeentry (); // 현재 zip 항목을 닫고 다음 항목 binstream.close ()를 작성하기 위해 스트림을 배치합니다. // instream.close ()를 닫습니다. }} else {Throw New ServleTeXception ( "파일이 존재하지 않습니다!"); }} catch (ioexception e) {Throw e; }}/** * 패키지 파일 다운로드 * * @param 파일 * @param 응답 */public static void downloadzip (파일 파일, httpservletResponse 응답) {// 파일을 스트림으로 다운로드합니다. bufferedInputStream fis = new bufferedInputStream (new FileInputStream (file.getPath ()); 바이트 [] buffer = new Byte [fis.available ()]; fis.read (버퍼); fis.close (); // 응답 응답을 클리어. reset (); outputStream toclient = new bufferedOutputStream (response.getOutputStream ()); Response.setContentType ( "Application/Octet-stream"); response.setheader ( "content-disposition", "첨부 파일; filename =" + file.getName ()); toclient.write (버퍼); toclient.flush (); toclient.close (); file.delete (); // 생성 된 서버 측 파일을 삭제} catch (ioexception ex) {ex.printstacktrace (); }} 위의 내용은 기본적으로 파일 업로드 및 다운로드 요구 사항을 충족합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.