할 일이 없으므로 업로드 및 다운로드 기능을 구현하기 위해 서물을 썼습니다. 서비스를 시작한 후 LAN에서 작은 파일 서버가 될 수 있습니다.
1. 준비
두 개의 JAR 패키지 다운로드 :
Commons-FileUpload-1.3.1.jar
Commons-IO-2.2.jar
2. 웹 프로젝트를 만듭니다
내 프로젝트는 z-upload라고합니다
3. Web.xml을 구성하십시오
<? xml version = "1.0"encoding = "utf-8"?> <web-app xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns = "http://java.sun.com/xml/ns/javaee" xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_3_0.xsd"3. ""webapp_ "" " <display-name> z-upload </display-name> <servlet> <servlet-name> 업로드-널리르시브 </servlet-name> <servlet-class> com.syz.servlet.uploadservice </servlet-class> </servlet> <servlet-mapping> <servlet-name> 업로드 letervice </url-pattern>/* </servlet-mapping> </web-app>
위의 구성에서 Servlet 클래스가 업로드 서비스이고 일치하는 URL이 /*임을 알 수 있습니다. 즉, 모든 액세스 URL과 일치하는 것을 의미합니다.
4. 서블릿 클래스를 쓰십시오
패키지 com.syz.servlet; import java.io.file; 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.text.text. java.util.date; import java.util.iterator; import java.util.list; import javax.servlet.servletcontext; import javax.servlet.servletexception; import javax.servlet.http.httpervlet; import javax.servlet.httpper.httppect. javax.servlet.http.httpervletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.progresslistener; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; public class uploadservlet httpservlet {public static final string list = "/list"; 공개 정적 최종 문자열 양식 = "/form"; 공개 정적 최종 문자열 핸들 = "/핸들"; 공개 정적 최종 문자열 다운로드 = "/다운로드"; 공개 정적 최종 최종 문자열 delete = "/delete"; 공개 정적 최종 문자열 업로드 _dir = "/Upload"; 개인 정적 최종 최종 긴 SerialversionUID = 2170797039752860765L; public void execute (httpservletrequest req, httpservletresponse resp) servletexception, ioexception {system.out.println ( "execute ..."); System.out.println ( "----------- 시작 ----------------"); req.setcharacterencoding ( "UTF-8"); 문자열 호스트 = req.getRemoteHost (); System.out.println ( "호스트 :" + host); String uri = req.getRequesturi (); System.out.println ( "uri :" + uri); ServletContext ServletContext = this.getServletConfig () .getServletContext (); // 파일을 업로드하는 기본 경로는 string basepath = servletcontext.getRealPath (upload_dir); // Context Path String ContextPath = servletContext.getContextPath (); System.out.println ( "ContextPath :" + ContextPath); // 컨텍스트를 가로 채운 후 경로 문자열 action = uri.substring (contextPath.length ()); System.out.println ( "action :" + action); // 다른 작업에 따라 다른 처리가 수행됩니다. if (action.equals (form)) {form (contextPath, resp); } else if (action.equals (handle)) {boolean ismultipart = servletfileupload.ismultipartContent (req); System.out.println ( "ismultipart :" + ismultipart); if (! ismultipart) {return; } diskFileItemFactory Factory = 새로운 DiskFileItemFactory (); 파일 리포지토리 = (파일) servletcontext .getAttribute (servletContext.tempdir); System.out.println ( "저장소 :" + repository.getabsolutepath ()); System.out.println ( "Basepath :" + Basepath); Factory.SetSizetHreshold (1024 * 100); Factory.SetRepository (저장소); ServletFileUpload 업로드 = 새로운 ServletFileUpload (공장); // 리스너 ProgressListener ProgressListener = New ProgressListener () {public void update (long pbytesread, long pcontentlength, int pitems) {System.out.println ( "현재 파일 크기 :" + pcontentLength + "/t 이미 처리 된 :" + pbyTesRead); }}; upload.setProgressListener (ProgressListener); 목록 <fileItem> 항목 = null; try {items = upload.parserequest (req); System.out.println ( "항목 크기 :" + items.size ()); iterator <fileitem> item = item.iterator (); while (ite.hasnext ()) {fileitem item = item.next (); if (item.isformfield ()) {// formfield} else {// 파일 핸들 문자열 fieldName = item.getFieldName (); 문자열 filename = item.getName (); filename = filename.substring (filename.lastindexof (file.separator) + 1); 문자열 contenttype = item.getContentType (); 부울 isinmemory = item.isinmemory (); Long SizeInbytes = item.getSize (); System.out.println (FieldName + "/t" + filename + "/t" + contentType + "/t" + isinMemory + "/t" + sizeInbytes); 파일 = 새 파일 (basepath + "/" + filename + "_" + getsuffix ()); // item.write (파일); inputStream in = item.getInputStream (); outputStream out = 새 FileOutputStream (파일); 바이트 [] B = 새로운 바이트 [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); 넣다(); out.close (); }} // 문자열을 처리 한 후 파일 목록 페이지로 리디렉션 href1 = contextPath + List; resp.sendredirect (href1); } catch (fileUploadeXception e) {e.printstacktrace (); } catch (예외 e) {e.printstacktrace (); }} else if (action.equals (list)) {list (contextPath, BasePath, resp); } else if (action.equals (다운로드)) {문자열 id = req.getParameter ( "id"); System.out.println ( "id :" + id); if (id == null) {return; } file file = 새 파일 (Basepath); file [] list = file.listfiles (); int len = list.length; 부울 플래그 = 거짓; for (int i = 0; i <len; i ++) {file f = list [i]; 문자열 fn = f.getName (); if (f.isfile () && fn.lastIndexof ( "_")> -1) {String fid = fn.substring (fn.lastIndexof ( "_")); if (id.equals (fid)) {download (f, resp); flag = true; 부서지다; }}} if (! flag) {notFound (ContextPath, resp); }} else if (action.equals (delete)) {문자열 id = req.getParameter ( "id"); System.out.println ( "id :" + id); if (id == null) {return; } file file = 새 파일 (Basepath); file [] list = file.listfiles (); int len = list.length; 부울 플래그 = 거짓; for (int i = 0; i <len; i ++) {file f = list [i]; 문자열 fn = f.getName (); if (f.isfile () && fn.lastIndexof ( "_")> -1) {String fid = fn.substring (fn.lastIndexof ( "_")); if (id.equals (fid)) {f.delete (); flag = true; 부서지다; }}} if (flag) {// 문자열을 처리 한 후 파일 목록 페이지로 리디렉션 href1 = contextPath + List; resp.sendredirect (href1); } else {notFound (ContextPath, resp); }} else {show404 (ContextPath, resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- printWriter = restwriter (); "<html>" 파일 목록으로 돌아가려면 </b> "); out.write ("</body> "); out.write ("</html> "); out.close ();} private void form (string contextpath, httpservletresponse resp)은 ioexception {resp.setContentType ("text/html; charset = utf-8 ")를 던집니다. resp.getWriter (); String href1 = 컨텍스트 + 목록 ( "<html>"); out.write ( "<head> <title> 양식 </title> </head>"); out.write ( "<body>"); out.write ( "<b> <a href = ' + href1 +"'> 클릭 </a> 파일 목록으로 돌아 가려면 </a>); out.write ( "<form action = 'handle'method = 'post'enctype = 'multipart/form-data'style = 'margin-top : 20px;'>"); out.write ( "<input name = 'file'type = 'file'/> <br>"); out.write ( "<input type = '제출'값 = '업로드'/> <br>"); out.write ( "</form>"); out.write ( "</body>"); out.write ( "</html>"); out.close (); } private void notFound (String ContextPath, httpservletResponse resp) IoException {resp.setContentType ( "text/html; charset = utf-8"); printwriter out = resp.getwriter (); 문자열 href1 = contextPath + 목록; out.write ( "<html> <body> <b> 작동 실패! 파일이 존재하지 않거나 파일이 삭제되지 않았거나 파일이 삭제되었습니다! <a href = '" + href1 + "'> 클릭 </a> 파일 목록으로 돌아 가려면 </b> </body> </html>"); out.close (); } private void download (file f, httpservletResponse resp) IoException {string fn = f.getName (); 문자열 filename = fn.substring (0, fn.lastindexof ( "_")); System.out.println ( "filename :" + filename); resp.Reset (); resp.setContentType ( "Application/Octet-stream"); String encodingFilename = new String (filename.getBytes ( "gbk"), "iso8859-1"); System.out.println ( "encodingFilename :" + encodingFilename); resp.SetHeader ( "내용화", "첨부 파일; filename =" + encodingFilename); inputStream in = new FileInputStream (f); outputStream out = resp.getOutputStream (); 바이트 [] B = 새로운 바이트 [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); 넣다(); out.close (); } private void list (문자열 contextPath, String BasePath, httpservletResponse resp) IoException {String href_u = contextPath + form; resp.setContentType ( "text/html; charset = utf-8"); printwriter out = resp.getwriter (); out.write ( "<html>"); out.write ( "<head> <title> 목록 </title> </head>"); out.write ( "<body>"); out.write ( "<b> <a href = '" + href_u + "'> 업로드 </a> </b> <br>"); out.write ( "<테이블 테두리 = '1'스타일 = 'Border-Collapse : 붕괴; 너비 : 100%; 마진-탑 : 20px;'>"); out.write ( "<thead>"); out.write ( "<tr>"); out.write ( "<th> 일련 번호 </th> <th> 파일 이름 </th> <th> Operation </th>"); out.write ( "</tr>"); out.write ( "</tr>"); out.write ( "<tbody>"); 파일 = 새 파일 (BasePath); file [] list = file.listfiles (); System.out .println ( "Basepath :" + Basepath + "/tlist.size :" + list.length); int len = list.length; int no = 1; for (int i = 0; i <len; i ++) {file f = list [i]; System.out.println (i + "/t" + f.getname ()); 문자열 fn = f.getName (); if (f.isfile () && fn.lastindexof ( "_")> -1) {String filename = fn.substring (0, fn.lastindexof ( "_")); 문자열 id = fn.substring (fn.lastindexof ( "_")); 문자열 href1 = contextPath + 다운로드 + "? id =" + id; 문자열 href2 = contextPath + delete + "? id =" + id; StringBuilder sb = new StringBuilder (); sb.append ( "<tr>"); sb.append ( "<td>"); sb.append (No ++); sb.append ( "</td>"); sb.append ( "<td>"); sb.append (filename); sb.append ( "</td>"); sb.append ( "<td>"); sb.append ( "<a href = '"); sb.append (href1); sb.append ( " '> 다운로드 </a> <a href ='"); sb.append (href2); sb.append ( " 'onclick ='return infiction (/"삭제 하려는가?/"); '> delete </a>"); sb.append ( "</td>"); sb.append ( "</tr>"); out.write (sb.tostring ()); }} out.write ( "</tbody>"); out.write ( "</table>"); out.write ( "</body>"); out.write ( "</html>"); out.close (); } public void doget (httpservletRequest req, httpservletResponse resp) servletexception, ioexception {system.out.println ( "doget ..."); execute (req, resp); } public void dopost (httpservletrequest req, httpservletResponse resp) servletexception, ioexception {system.out.println ( "dopost ..."); execute (req, resp); } private string getSuffix () {날짜 날짜 = 새 날짜 (); simpledateformat sdf = new simpledateformat ( "yyyymmddhhmmssss"); 문자열 접미사 = sdf.format (날짜); 반환 접미사; }}실제로 업로드 서비스 클래스는 doget 및 dopost 메소드를 구현하지 않고 서비스 방법을 직접 구현할 수 있습니다.
위의 서블릿에 대해 설명하고 싶지는 않지만 직접 코드를 읽으십시오.
5. 복제 다이어그램
1. 프로젝트 구조 다이어그램
2.404 페이지
/*는 모든 null 문자와 일치하므로 그림의 경로가 일치합니다.이 시간의 동작은 Null 문자이기 때문에 업로드 서비스의 IF 판단에 다른 사람에 나타납니다.
3. 파일 목록 페이지
4. 양식 페이지 업로드
5. 다운로드
6. 삭제
7. 파일을 찾을 수 없습니다. 삭제를 클릭하면 서버에 파일이 더 이상 존재하지 않으면이 페이지를 입력합니다.
8. 포장 소스 코드 프로젝트 및 전쟁 패키지
그중 Z-upload는 Eclipse 소스 코드 프로젝트이며 z-upload.war는 Ready War 패키지입니다.
전체 프로젝트에는 2 개의 JAR 패키지, 하나의 web.xml 및 1 개의 서블릿 클래스 만 있습니다. 기사에서 복사하여 테스트 할 수 있습니다. 게으른 경우 다운로드 할 수 있습니다.
http://download.csdn.net/detail/yunsyz/9569680, Special Requinder, 1 포인트로 다운로드하십시오.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.