Javaweb에서 업로드 및 다운로드는 일반적인 기능입니다. 파일 업로드의 경우 브라우저는 스트리밍 프로세스에서 파일을 업로드하는 프로세스에서 파일을 서버로 전달합니다. 일반적으로 Commons-FileUpload 패키지는 업로드 기능을 구현하는 데 사용됩니다. Commons-FileUpload는 Commons-IO 패키지에 따라 달라 지므로이 두 패키지 Commons-FileUpload-1.2.1.jar 및 Commons-IO-1.3.2.jar를 다운로드해야합니다.
1. 환경을 구축하십시오
웹 프로젝트를 만들고 패키지를 프로젝트 LIB로 가져옵니다.
2. 파일 업로드를 구현하십시오
(업로드의 첫 번째 방법)
새 upload.jsp 페이지를 만듭니다
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/html4/loose.dtd"> html> html> http-tequiv ="content-type "content ="text/html; charset = utf-8 "> </title> </head> <!-<bet the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the title> </head> <). 프로젝트에 대한 절대 경로는 미래에 프로젝트를 어디에서 복사하든 정확한 경로를 찾을 수 있음을 의미합니다.-> <form action = "<%= request.getContextPath ()%>/uploadServlet"EncType = "multipart/form-data"method = "post"> </span> <input type = "file ="file = "input type ="input ""pute = "input" "post". </form> </body> </html>
파일 업로드를 처리하는 새 서블릿을 만듭니다
패키지 com.load; import java.io.file; import java.io.ioexception; import java.util.list; import javax.servlet.servletcontext; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http 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; @webservlet ( "/uploadservlet") public class uploadservlet httpservlet {private static final long serialuid = 1l; public uploadservlet () {super (); } /* FileUpload 패키지에서 HTTP 요청의 복잡한 양식 요소는 FileItem 객체로 간주됩니다. * fileItem 객체는 servletfileUpload 클래스* (즉, 랩핑 된 httpservletRequest 객체)의 parserequest () 메소드에 의해 구문 분석되어야합니다. 즉, 특정 텍스트 양식 및 업로드 파일은 분리되어 있습니다**/Protected void doget (httpservletRequest 요청, httpervletRescone resigns). ISMULTIPARTCONTENT () 메소드 : 요청에 파일에 요청이 있는지 분석, 부울 ismultipart = servletfileUpload.ismultipartContent (요청); if (ismultipart) {// Settable Disk Node Factory DiskFileItemFactory Factory = New DiskFileItemFactory (); // 요청 요청 servletContext servletContext = request.getServletContext ()의 컨텍스트 정보 가져옵니다. // 캐시 디렉토리, 각 서버 별 디렉토리 파일 리포지토리 = (파일) servletcontext.getAttribute ( "javax.servlet.context.tempdir"); // 서버의 캐시 디렉토리 공장을 설정합니다. // servletfileUpload 객체의 생성은 fileItemFactory에 의존해야합니다. // 팩토리는 획득 한 업로드 파일 파일 객체를 서버 하드 디스크, 즉 디스크 파일 객체에 저장합니다. ServletFileUpload 업로드 = 새로운 ServletFileUpload (공장); {// 텍스트 양식 및 파일을 분리하는 후 httpservletrequest 객체를 구문 분석합니다 (http request는 httpservletrequest로 랩핑됩니다) 목록 <fileitem> items = upload.parseerequest (요청); for (fileItem item : items) {String fieldName = item.getFieldName (); 문자열 filename = item.getName (); 문자열 contenttype = item.getContentType (); 부울 isinmemory = item.isinmemory (); Long SizeInbytes = item.getSize (); // 파일을 인스턴스화 // request.getRealPath (실제 경로 가져 오기) 파일 파일 = 새 파일 (request.getRealPath ( "/")+"/loads"+filename.substring (filename.lastIndexOf ( "//")+1, filename.length ()); item.write (파일); }} catch (fileUploadexception e) {e.printstacktrace (); } catch (예외 e) {e.printstacktrace (); }}} Protected Void Dopost (httpservletrequest 요청, httpservletResponse 응답) servletexception, ioexception {doget (요청, 응답); }}(두 번째 업로드 방법)
새 JSP 페이지 생성 (위와 동일, 경로 만 변경됨)
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/html4/loose.dtd"> html> html> http-tequiv ="content-type "content ="text/html; charset = utf-8 "> </title> </head> <!-<bet the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the title> </head> <). 프로젝트에 대한 절대 경로는 미래에 프로젝트를 어디에 있든 정확한 경로를 찾을 수 있음을 의미합니다.> <form action = "<%= request.getContextPath ()%>/uploadServlet1"EncType = "multipart/form-data"method = "post"> <span> </span> <input type = "file ="input = "input =" "value ="input ". </form> </body> </html>
업로드를 처리 할 서블릿을 만듭니다
패키지 com.load; import java.io.file; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStream; import java.io.outputstream; import javax.servlet.servletexception; import javax.servlet.annotation.multipartconfig; import; javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpervletresponse; import javax.servlet.http.part; @webservlet ( "/uploadservlet1")@multipartconfig (location = "" ") public class uploadservlet1 httpservlet {private static final long serialversionuid = 1L; public uploadservlet1 () {super (); } Protected void doget (httpservletrequest 요청, httpservletResponse 응답)은 servletexception, ioexception {response.setContentType ( "text/html; charset = utf-8"); request.setcharacterencoding ( "UTF-8"); // 파일을 업로드하고 파일을 읽습니다. // 파일 이름을 수신 할 변수를 정의하십시오. string filename = null; // content-disposition : 사용자가 요청 된 컨텐츠를 파일로 저장하려면 기본 파일 이름을 제공하는 것입니다. // content-disposition : (문자열 내용 : part.getheader ( "content-disposition"). split ( ";")) {system.out.println (content); // if (content.trim (). startswith ( "filename"))) {// 파일 이름 filename = content.substring (content.indexof ( '=')) + 1) .trim (). replace ( "/" ",", ");}} // outputStream out = null; // incontrest the null the null. 시스템의 구분 = 새로운 파일 (e :/loads " + file.separator + filename); 읽기);(업로드의 세 번째 방법)
JSPSMARTUPLOAD 패키지는 여기에서 업로드 및 다운로드하는 데 사용됩니다. 저자는 이런 종류의 업로드 및 다운로드는 비교적 간단하다고 생각하지만 많은 사람들이 사용하지 않고 이해하지 못하는 것 같습니다.
HTML 페이지를 만듭니다
<! docType html> <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"> <title> 파일 업로드 파일 </head> <body> <p> </p> <p align = "center </p> </p> <action ="action = "action ="action = " EncType = "multipart/form-data"> <table align = "center"> <tr> <td> <div align = "center"> 1. <입력 유형 = "file"name "="file1 "> </div> </td> </tr> <tr> <td> <div align ="center "> 2 <input type ="file ""file ""file "> <tr> <td> align = "center"> 3. <input type = "file"name = "file3"> </div> </td> </tr> <td> <div align = "center"> <input type = "value ="value = "upload"> </td> </td> </ht> </table> </table>
업로드 파일을 처리 할 서플렛을 만듭니다
패키지 com.load; import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.httplet.httpepest.; Javax.servlet.http.http.httpervletresponse; import javax.servlet.jsp.jspfactory; import javax.servlet.jsp.pagecontext; import com.jspsmart.upload.file; import com.jspsmart.upload.smartupload; import com.jspsmart.upload.smartuploadexception; @webservlet ( "/douploadservlet") public class downloadservlet는 httpservlet {private static final long serialversionuid = 1l을 확장합니다. public downloadservlet () {super (); } Protected void doget (httpservletrequest 요청, httpservletResponse 응답)은 servletexception, ioexception {response.setContentType ( "text/html; charset = utf-8"); printwriter out = response.getwriter (); // 새 스마트 업로드 객체 생성 smartUpload su = new SmartUpload (); / * * pagecontext pagecontext; httpsession 세션; ServletContext 응용 프로그램; ServletConfig 구성; JSPWRIRTER; 객체 페이지 = 이것; httpservletrequest 요청, httpservletresponse 응답 페이지 객체, 요청 및 응답이 인스턴스화되는 반면, 인스턴스화되지 않은 다른 5 개 객체는 다음과 같은 방식으로 인스턴스화됩니다. */// JSP Factory Class PageContext pagecontext = jspfactory.getDefaultFactory ()를 통해 컨텍스트 환경을 얻습니다. // 업로드 초기화 su.initialize (pagecontext); // 파일 업로드 시도 {su.upload (); // 지정된 디렉토리에 업로드 파일을 저장 int count = su.save ( "/share"); out.println (count+"파일 업로드가 성공적으로 업로드! <br>"+su.tostring ()); } catch (smartUploadexception e) {e.printstacktrace (); } // (int i = 0; i <su.getfiles (). getCount (); i ++) {file file = su.getFiles (). getFile (i); // 파일이 존재하지 않는 경우 (file.ismissing ())가 계속; // 현재 파일 정보 표시 out.println ( "<테이블 테두리 = 1>"); out.println ( "<tr> <td> 양식 항목 이름 (FieldName) </td> </td>"+file.getFieldName ()+"</td> </tr>"); out.println ( "<tr> <td> 파일 길이 </td> <td>"+file.getSize ()+"</td> </tr>"); out.println ( "<tr> <td> 파일 이름 </td> <td>"+file.getFilename ()+"</td> </tr>"); out.println ( "<tr> <td> 파일 이름 </td> <td>"+file.getFilename ()+"</td> </tr>"); out.println ( "<tr> <td> 파일 확장 </td> <td>"+file.getFileExt ()+"</td> </tr>"); out.println ( "<tr> <td> 파일 전체 이름 </td> <td>"+file.getFilePathName ()+"</td> </tr>"); out.println ( "</table> <br>"); }} / ** * @ @httpservlet#dopost (httpservletrequest request, httpservletresponse response) * / protected void dopost (httpservletrequest 요청, httpservletrepsonse 응답) servletexception, ioexception, ioexception, ioexception {// wor auto-genderated method (요청, 응답); }} 참고 : 코드 int count = su.save ( "/share"); 먼저 폴더를 만들어야하므로 먼저 WebContent에서 폴더를 작성한 다음 프로젝트를 분리 한 다음 재배치하면 폴더가 실행 측면에서 생성됩니다!
또는 실행 및 공유 폴더를 직접 찾을 수 있습니다.
3. 파일 다운로드 실현
(첫 번째 파일 다운로드)
참고 :이 코드는 Servlet 클래스에 직접 액세스합니다
패키지 com.load; import java.io.fileInputStream; import java.io.ioException; import java.io.inputStream; import java.io.outputStream; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.httperver; javax.servlet.http.httpervletrequest; import javax.servlet.http.htttp.httpservletresponse; // http : // localhost : 8080/test1/다운로드 다운로드를 직접 사용하지만 이것은 결함이 있습니다. 다운로드 파일 이름에 중국어가 있으면 차가워집니다! @webservlet ( "/download") public class 다운로드 확장 httpservlet {private static final long serialversionuid = 1l; public download () {super (); } Protected void doget (httpservletrequest 요청, httpservletreponse 응답)은 servletexception, ioexception {response.setContentType ( "text/plain; charset = utf-8"); 응답 .SetchAracterEncoding ( "UTF-8"); Response.SetHeader ( "위치", "중국어 .txt"); response.setheader ( "Content-Disposition", "첨부 파일; filename =" + "account.txt"); outputStream outputStream = response.getOutputStream (); inputStream inputStream = 새로운 fileInputStream ( "e :/loads"+"/account.txt"); 바이트 [] 버퍼 = 새로운 바이트 [1024]; int i = -1; while ((i = inputStream.read (buffer))! = -1) {outputStream.write (buffer, 0, i); } outputStream.flush (); outputStream.close (); } 보호 된 void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {doget (요청, 응답); }}(두 번째 다운로드 방법)
새 JSP 페이지를 만들고 다운로드를 선택하십시오
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/tr/html4/loose.dtd"> html> html> http-quiv ="content-type "content ="text/html; charset = utf-8 "> </title> </head> <a href = "../ dodownloadservlet? filename = hehe.txt"> 다운로드하려면 클릭하십시오 </a> </body> </html>
다운로드 할 서블릿 클래스를 만듭니다 (참고 :이 다운로드의 파일 이름이 중국인 인 경우 여전히 garbled 코드가 발생합니다).
패키지 com.load; import java.io.bufferedInputStream; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputStream; import java.net.urlencoder; import javax.servlet.servletexcement; javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.jsp.jspfactory; javax.servlet.jsp.PageContext;import org.hsqldb.lib.StringUtil;import com.jspsmart.upload.SmartUpload;import com.jspsmart.upload.SmartUploadException;@WebServlet("/DoDownloadServlet")public class DoDownloadServlet extends HttpServlet { private static final 긴 SerialversionUID = 1L; public dodownloadservlet () {super (); } protected void doget (httpservletrequest request, httpservletResponse 응답) servletexception, ioexception {// 다운로드 된 파일의 이름 가져 오기 // string filename = request.getParameter ( "filename"); // string filename = new String (filename.getBytes ( "iso8859-1"), "utf-8"); // 새 smartUpload 객체 생성 smartUpload su = new SmartUpload (); pagecontext pagecontext = jspfactory.getDefaultFactory (). getPageContext (this, request, response, null, true, 8192, true); // 초기화 업로드 su.initialize (pagecontext); // 파일의 시작을 금지하는 설정 su.setContentDisPosition (null); // 다운로드 파일 try {su.downloadfile ( "/listener/"+filename); } catch (smartUploadexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} 보호 된 void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {doget (요청, 응답); }}(세 번째 다운로드 방법)
위와 동일한 JSP 페이지 코드는 여기에서 반복되지 않습니다.
다운로드 기능을 구현하기 위해 새 Serlvet 클래스를 만듭니다 (참고 : 파일 이름이 중국 이름이더라도 문제가 없을 것입니다!)
패키지 com.load; import java.io.bufferedInputStream; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputStream; import java.net.urlencoder; import javax.servlet.servletexcement; javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.jsp.jspfactory; javax.servlet.jsp.PageContext;import org.hsqldb.lib.StringUtil;import com.jspsmart.upload.SmartUpload;import com.jspsmart.upload.SmartUploadException;@WebServlet("/DoDownloadServlet")public class DoDownloadServlet extends HttpServlet { private static final 긴 SerialversionUID = 1L; public dodownloadservlet () {super (); } Protected void doget (httpservletrequest 요청, httpservletResponse 응답) servletexception, ioexception {// 파일 이름 String path1 = request.getParameter ( "filename"); // path 이름 문자열 path = requestSession (). getServletContext (). getRealPath ( "/LEARTER/"+PATH1); // 경로는 로그 경로와 파일 이름을 기반으로 스 플라이밍 된 파일입니다. 문자열 filename = file.getName (); 시도 {// IE11 부울 플래그 = request.getheader ( "user-agent"). indexof ( "Gecko")> 0; // IE11 사용자 에이전트 문자열 : Mozilla/5.0 (Windows NT 6.1; Wow64; Trident/7.0; RV : 11.0) Gecko // IE6 ~ IE10 버전 사용자 에이전트 문자열 : Mozilla/5.0 (MSIE 10.0; Windows NT 6.0; Trident/6.0) IF (request.getheader ( "user-agent"). tolowercase (). indexof ( "msie")> 0 || flag) {filename = urlencoder.encode (filename, "utf-8"); // browser} else {// 첫 번째 파일 이름에서 공백을 제거한 다음 Encoding Format을 해체로 변환합니다. //이 파일 이름은 브라우저의 다운로드 박스에 자동으로 표시된 파일 이름에 사용됩니다. filename = new String (filename.replaceall ( "", "") .getBytes ( "UTF-8"), "ISO8859-1"); // Firefox 브라우저 // Firefox 브라우저 사용자-에이전트 문자열 : //mozilla/5.0 (Windows NT 6.1; WOW64; RV : 36.0) Gecko/20100101 Firefox/36.0} inputStream fis = new bufferedInputStream (new FileInputStream (path)); 바이트 [] 버퍼; 버퍼 = 새 바이트 [fis.available ()]; fis.read (버퍼); fis.close (); response.reset (); response.addheader ( "Content-Disposition", "첨부 파일; filename =" +filename); response.addheader ( "Content-Length", "" + file.length ()); outputStream os = response.getOutputStream (); Response.setContentType ( "Application/Octet-stream"); os.write (buffer); // 출력 파일 os.flush (); os.close (); } catch (ioexception e) {e.printstacktrace (); } system.out.println (filename); } 보호 된 void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {doget (요청, 응답); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.