기능 파일의 업로드, 다운로드 및 관리 기술 : 1. XML 사용 데이터베이스 스토리지 정보 (DOM4J, XPATH)
2. Java Forms의 업로드 및 다운로드
3. 파일 디렉토리 해체 (해시 디렉토리는 파일 스토리지 성능을 최적화하는 방법입니다)
JAR 패키지 필요 :
Commons-FileUpload-1.2.2.jar, Commons-IO-2.1.jar, dom4j-1.6.1.jar 및 Jaxen-1.1-Beta-6.jar
-----------------------------------------------------------------------------------------
먼저 index.jsp를 작성하십시오
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en"> <html> <head> <title> 앨범 관리 시스템 </head> <h1> </h1> <h1> <h1> href = "jsps/upload.jsp"> 앨범 업로드 </a> <a href = "servlets/showservlet"> 앨범 찾아보기 </a> </body> </html>
upload.jsp는 JSPS 디렉토리에있는 다운로드 페이지입니다.
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtd html 4.01 Transitional // en"> <html> <head> </head> <body> <h1> uploading </h1> <form action = "<%= request.getConteptPath ()%>/servlets/uploadservlet"method = "post"enctype = "multipart/form-data"> file : <input type = "file"name = "file1"/> <br/> description : <input type = "text"name = "desc"/>> <input type = "value ="upply "/> </form> </body> </html>
SRC 디렉토리에 photos.xml을 넣으십시오
<? xml 버전 = "1.0"encoding = "utf-8"?> <photos> </photos>
값 객체 광도상을 작성하십시오
패키지 CN.HNCU.DEMAIN; Public Class Photomodel {개인 문자열 ID; 개인 문자열 실재; 개인 문자열 내선; 개인 문자열 dir; 개인 문자열 dateTime; 개인 문자열 IP; 개인 문자열 desc; public String getId () {return id; } public void setId (String id) {this.id = id; } public String getRealName () {return RealName; } public void setRealName (String realName) {this.RealName = realName; } public String getext () {return ext; } public void setext (String Ext) {this.ext = ext; } public String getDir () {return dir; } public void setdir (String dir) {this.dir = dir; } public String getDateTime () {return dateTime; } public void setDateTime (String dateTime) {this.dateTime = dateTime; } public String getIP () {return IP; } public void setip (String IP) {this.ip = ip; } public String getDesc () {return desc; } public void setdesc (String desc) {this.desc = desc; } @Override public String toString () {return "photomodel [id =" + id + ", realName =" + realName + ", ext =" + ext + ", dir =" + dir + ", dateTime =" + dateTime + ", ip =" + ip + ", desc =" + desc + "]; }} 작문 도구에는 두 가지 유형이 있습니다.
myutil (날짜 형식, 디렉토리 파괴 코드, 랜덤 ID 코드)
패키지 cn.hncu.utils; import java.text.simpledateformat; import java.util.date; import java.util.uuid; public class myutils {private myutils () {} private static simpledateformat format = new SimpledateFormat ( "Yyyyyy Year mm mp.); public static string getCurrentDateTime () {return format.format (new Date ()); } public static string getUuid () {uuid uuid = uuid.randomuuid (); 문자열 id = uuid.tostring (). replaceall ( "-", ""); 반환 ID; } public static string getDir (String UUID) {String dir1 = integer.toHexString (uuid.hashCode () & 0xf); 문자열 dir2 = integer.tohexstring ((uuid.hashcode () & 0xf0) >> 4); 반환 dir1+"/"+dir2; }}dom4jfactory (dom4j의 관련 작업, 문서 개체 얻기, 작업 저장)
패키지 cn.hncu.utils; import java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.fileoutputStream; import java.io.unsupportedEncodexception; import org.dom4j.document; import org.documentcement; org.dom4j.io.outputformat; import org.dom4j.io.saxreader; import org.dom4j.io.xmlwriter; public class dom4jfactory {private static document dom = null; 개인 정적 문자열 경로; static {try {saxreader sax = new SaxReader (); // 서버에서 리소스 경로를로드하는 방법을 배웁니다 (우리의 리소스가 MyEclipse에서 Tomcat 서버로 게시되었으므로 원래 Pure Java 프로젝트와 다릅니다) // 현재 클래스를 사용하여 클래스 로더를 찾은 다음 클래스 로더를 사용하여 리소스 경로를 사용하여 Resource Path = dom4jactory.class.get ClassLoader ( "getResource ("). dom = sax.read (new FileInputStream (Path)); } catch (예외 e) {새로운 runtimeexception 던지기 (e.getMessage (), e); }} public static document getdom () {return dom; } public static boolean save () {try {outputformat format = new outputformat (); format.setencoding ( "UTF-8"); xmlwriter w = new xmlwriter (new FileOutputStream (새 파일 (path)), 형식); W.Write (dom); w.close (); 진실을 반환하십시오. } catch (예외 e) {return false; }}}하단 레이어에서 Photodao를 작성하십시오
패키지 cn.hncu.dao; import java.util.arraylist; import java.util.iterator; import java.util.list; import org.dom4j.document; import org.dom4j.element; import cn.hncu.demain.photomodel; import clate problic {addom4jfortory; 부울 추가 (Photomodel photo) {document dom = dom4jfactory.getdom (); 요소 root = dom.getRootElement (); 요소 ephoto = root.addelement ( "photo"); ephoto.addattribute ( "id", photo.getId ()); ephoto.addattribute ( "RealName", photo.getRealName ()); ephoto.addattribute ( "dir", photo.getDir ()); ephoto.addattribute ( "ip", photo.getip ()); ephoto.addattribute ( "dateTime", photo.getDateTime ()); ephoto.addattribute ( "ext", photo.getext ()); ephoto.addelement ( "desc"). settext (photo.getDesc ()); boolean boo = dom4jfactory.save (); 반환 부; } // public List를 찾아보기 <Photomodel> getAll () {document dom = dom4jfactory.getDom (); 목록 <photomodel> list = new arraylist <photomodel> (); 요소 root = dom.getRootElement (); iterator <ELTECT> IT = root.elementIterator (); while (it.hasnext ()) {photomodel photo = new Photomodel (); 요소 e = it.next (); photo.setId (e.attributeValue ( "id")); photo.setDateTime (e.attributeValue ( "dateTime")); photo.setdir (e.attributeValue ( "dir")); photo.setext (e.attributeValue ( "ext")); photo.setip (e.attributeValue ( "IP")); photo.setRealName (e.attributeValue ( "realName")); photo.setdesc (e.elementText ( "desc")); list.add (사진); } 반환 목록; } public photomodel getSingleById (String id) {document dom = dom4jfactory.getDom (); 목록 <photomodel> list = getall (); for (photomodel photo : list) {if (photo.getId (). equals (id)) {return photo; }} return null; } public boolean del (문자열 id) {document dom = dom4jfactory.getdom (); 요소 e = (요소) dom.selectsingLenode ( "// photo [@id = '+id.trim ()+"'] "); return e.getParent (). 제거 (e); }} 마지막에 4 개의 서블릿을 작성하십시오
업로드 서비스 업로드 서비스 코드 업로드
패키지 CN.hncu.servlets; import java.io.file; import java.io.ioexception; import java.io.inputstream; import java.io.printwriter; import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpervlet; javax.servlet.http.httpervletrequest; import javax.servlet.http.htttp.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.io.fileutils; import cn.hncu.dao.photodao; import cncu.hotodel; cn.hncu.utils.myutils; public class uploadservlet는 httpservlet {public void doget (httpservletrequest request, httpservletreponse 응답)을 servletexception, ioexception {response.setcontenttype ( "text/html = utf-8"); printwriter out = response.getwriter (); out.println ( "<! doctype html public/"-// w3c // dtd html 4.01 Transitional // en/">"); out.println ( "<html>"); out.println ( "<head> <title> a servlet </title> </head>"); out.println ( "<body>"); out.println ( "Get 업로드는 지원되지 않습니다!"); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {response.setContentType ( "text/html; charset = utf-8"); printwriter out = response.getwriter (); 문자열 path = request.getServletContext (). getRealPath ( "/photos"); DiskFileItemFactory Factory = 새로운 DiskFileItemFactory (); factory.setRepository (새 파일 ( "g :/a"); ServletFileUpload 업로드 = 새로운 ServletFileUpload (공장); upload.setsizemax (1024*1024*10); // 최대 10m 업로드 .setheaderEncoding ( "UTF-8"); // 파일 이름의 인코딩을 설정하는 데 : request.SetchAracterEncoding ( "UTF-8"); fileItem fi = null; try {list <fileitem> list = upload.parserequest (요청); Photomodel photo = new photomodel (); // 데이터 캡슐화 --- 7 속성이 필요합니다. 부울 부 = false; inputStream in = null; for (fileitem fi2 : list) {fi = fi2; if (fi.isformfield ()) {String desc = fi.getString ( "utf-8"); photo.setdesc (desc); // desc} else {in = fi.getInputStream (); 문자열 realName = fi.getName (); if (realName == null || realName.trim (). equals ( "")) {out.print ( "파일 없음!"); 반품; } if (realName.indexOf ( "//")! = -1) {realName = realName.SubString (realName.lastIndexOf ( "//")+1); } photo.setRealName (realName); // real 파일 이름 문자열 ext = realName.SubString (realName.LastIndexOf ( ".")); photo.setext (ext); // 3 photo.setDateTime (myUtils.getCurrentDateTime ()); // 4 photo.setId (myUtils.getUuid ()); // 5 photo.setDir (myUtils.getDir (photo.getId ()); // 6 photo.setip (request.} // 7})); 데이터베이스 photodao dao = 새로운 photodao (); boo = dao.add (사진); // 위의 사진 정보가 성공적으로 저장되면 이미지 파일을 수신하고 서버 하드 디스크에 저장하기 시작하면 (boo) {System.out.println (dao); Path = Path+"/"+photo.getDir (); 파일 dir = 새 파일 (경로); if (! dir.exists ()) {dir.mkdir (); } 문자열 filename = path+"/"+photo.getId ()+photo.getext (); fileUtils.copyInputStreamTofile (in, 새 파일 (filename)); 문자열 strath = request.getContextPath ()+"/servlets/showservlet"; out.print ( "성공적으로 업로드! <a href = '"+stratp+"'> 앨범 찾아보기 </a>"); } else {out.print ( "업로드 실패!"); }} catch (fileUploadexception e) {throw new runtimeexception ( "업로드 실패!"); ", e);} 마침내 {if (fi! = null) {fi.delete ();}} out.flush (); out.close ();}}Showservlet 앨범을 탐색하는 앨범의 서블릿 쪽
패키지 cn.hncu.servlets; import java.io.ioexception; import java.io.printwriter; import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.httplet.httpert.httpertreport javax.servlet.http.http.httpervletresponse; import cn.hncu.dao.photodao; import cn.hncu.demain.photomodel; public class showservlet가 httpservlet을 확장합니다. servletexception, ioexception {dopost (요청, 응답); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {response.setContentType ( "text/html; charset = utf-8"); request.setcharacterencoding ( "UTF-8"); printwriter out = response.getwriter (); out.println ( "<! doctype html public/"-// w3c // dtd html 4.01 Transitional // en/">"); out.println ( "<html>"); out.println ( "<head> <title> a servlet </title> </head>"); out.println ( "<body>"); 문자열 테이블 = "<테이블 테두리 = '1'width = '100%'>"+ "<tr> <th> 파일 이름 </th> <th> 업로드 ip </th> <th> 업로드 시간 </th> <th> 이미지 </th> <th> 명령어 </th> <t> Operation </th> </tr>"; out.print (표); photodao dao = 새로운 photodao (); 목록 <photomodel> list = dao.getall (); for (photomodel p : list) {out.print ( "<tr>"); out.println ( "<td>"+p.getRealName ()+"</td>"); out.println ( "<td>"+p.getip ()+"</td>"); out.println ( "<td>"+p.getDatetime ()+"</td>"); // 출력 사진 문자열 경로 = request.getContextPath ()+"/photos/"+p.getDir ()+"/"+p.getId ()+p.getext (); out.println ( "<td> <a href = '"+path+"' '> <img src ='"+path+" 'width ='200 'height ='200 '> </img> </a> </td>"); String op = "<a href = '"+request.getContextPath ()+"/servlets/delservlet? id ="+p.getId ()+"'> delete </a>"; out.println ( "<td>"+p.getDesc ()+"</td>"); op+= "<a href = '"+request.getContextPath ()+"/servlets/downservlet? id ="+p.getId ()+"'> 다운로드 </a>"; out.println ( "<td>"+op+"</td>"); out.print ( "</tr>"); } out.println ( "</table>"); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); }}DownServlet에서 다운로드 한 서버 코드
패키지 CN.hncu.servlets; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStream; import java.io.outputStream; import java.io.printwriter; import java.net.ba.net.nocoder; javax.servlet.http.httpservlet; import javax.servlet.http.htttp.httpservletrequest; import javax.servlet.http.http.htttp.httpervletresponse; import cn.hncu.dao.photodao; import cn.hncu.demain.photomodele; {public void doget (httpservletrequest request, httpservletresponse 응답) servletexception, ioexception {dopost (요청, 응답); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {string id = request.getParameter ( "id"); Response.setContentType ( "응용 프로그램/포스 다운로드"); Photomodel p = new photodao (). getsingleByid (id); if (p! = null) {String realName = p.getRealName (); realName = new String (realName.getBytes ( "iso8859-1"), "UTF-8"); response.setHeader ( "내용화", "첨부 파일; filename =/" "+realName+"/""); String relpath = getServletContext (). getRealPath ( "/photos/"+p.getDir ()+"/"+p.getId ()+p.getext ()); inputStream in = new FileInputStream (relpath); outputStream out = response.getOutputStream (); System.out.println (relpath); 바이트 buf [] = 새로운 바이트 [1024]; int len = 0; while ((len = in.read (buf))! = -1) {out.write (buf, 0, len); } out.close (); } else {response.setContentType ( "text/html; charset = utf-8"); Response.getWriter (). println ( "이 파일이 삭제되었습니다!"); }}}delservlet 삭제 서버
패키지 cn.hncu.servlets; import java.io.file; import java.io.fileInputStream; import java.io.ioException; import java.io.inputStream; import java.io.outputStream; import java.io.printwriter; import javax.servletex; import javax.servlet.http.httpservlet; import javax.servlet.http.httpervletrequest; import javax.servlet.http.http.http.httpervletresponse; import cn.hncu.dao.photodao; import cn.hncu.demain.photomodele; {public void doget (httpservletrequest request, httpservletresponse 응답) servletexception, ioexception {dopost (요청, 응답); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {request.setcharacterencoding ( "utf-8"); Response.setContentType ( "Text/Html; charset = utf-8"); printwriter out = response.getwriter (); 문자열 id = request.getParameter ( "id"); Photomodel p = new photodao (). getsingleByid (id); if (p! = null) {if (! p.getip (). equals (request.getRemoteaddr ())) {out.println ( "삭제할 권한이 없습니다!"); 반품; } // ※※※※ 다음 부분이 다음 클래스에 추가됩니다 !!! // 1Delete 데이터베이스 Photodao dao = new Photodao (); 부울 boo = dao.del (id); // 2Delete 서버 하드 디스크에서 파일을 2Delete if (boo) {String filename = "photos/"+p.getDir ()+"/"+p.getId ()+p.getext (); String PathFilename = GetServletContext (). getRealPath (filename); 파일 f = 새 파일 (pathfilename); if (f.exists ()) {f.delete (); } string strath = request.getContextPath ()+"/servlets/showservlet"; out.println ( "사진은 성공적으로 삭제! <a href = '"+strpath+"'> 앨범 브라우즈 </a>"); } else {out.println ( "사진 삭제 실패!"); }} else {response.setContentType ( "text/html; charset = utf-8"); response.getWriter (). println ( "이 파일이 존재하지 않습니다!"); }}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.