웹 파일 업로드는 게시물을 사용합니다. 포스트 제출 양식 제출과 달리 파일 업로드는 양식의 ENCTEPE 속성을 멀티 파트/양식 데이터로 설정해야합니다. 업로드 된 파일이 비교적 크기 때문에이 매개 변수는 브라우저가 이진 업로드를 사용하도록 지정하도록 설정해야합니다. 설정하지 않으면 ENCTERPE 속성은 기본적으로 응용 프로그램/x-www- 형태로 인코딩됩니다. 브라우저를 사용하면 ASCII를 사용하여 서버로 데이터를 전송하여 파일을 전송하지 않습니다.
파일을 업로드하려면 파일 도메인 (<input type = 'file'/>을 사용하고 양식의 ENCTEPE를 멀티 파트/양식 데이터로 설정하십시오.
클라이언트 업로드 페이지가 그림에 표시됩니다.
코드는 다음과 같습니다.
upload.html
<! docType html public "-// w3c // dtd html 4.01 전환 // en"> <html> <html> <html> <html> <html> <html> <title> 파일 업로드 </title> <meta http-equiv = "keyword1, keyword2, keyword3"> <meta http- equiv = "desction ="this is is is is is is is descment =. http-equiv = "content-type"content = "text/html; charset = utf-8"> <link rel = "stylesheet"type = "text/css"href = "css/style.css"> </head> <body action = "servlet/uploadservlet"inctart/uploadservlet = "acttart/uploadservlet"<actart/uploadservle align="center"><br/> <fieldset> <legend>Upload file</legend><br/> <div class='line'> <div align='left'>Upload file 1</div> <div align='left'> <input type="file" name="file1"> </div> </div> <div class='line'> <div align='left'>Upload file 2</div> <div align = 'left'> 업로드 파일 2 </div> <div align = 'left'> align = 'left'> <input type = "file"name = "file"> </div> </div> <div class = 'line'> <div '> 업로드 파일 설명 1 </div> <div align ='left '> <input type = "text"name = "text" "name" "name" "</div> <input type =. class = 'line'> <div align = 'left'> 파일 업로드 파일 설명 2 </div> <div align = 'left'> <input type = "text"name = "description2"> </div> </div> <div class = 'line'> <div align = 'left'> 업로드 파일 설명 2 </div> <div align = 'left'> <div align = '<br/> <bl'> <bl '> 값 = "파일 업로드"> </div> </div> </fieldset> </div> </form> </body> </html>
클라이언트가 실행하는 코드는 매우 간단하며 서버는 더 복잡합니다. 내용을 얻으려면 브라우저에서 제출 한 요청은 HTTP 프로토콜에서 지정된 형식에 따라 구문 분석해야합니다.
이진 스트림을 구문 분석하는 것이 더 번거 롭습니다. 많은 수업 도서관이 이미이 작업을 완료했습니다. 예를 들어 SmartUpload 및 Apache Commons FileUpload.smartupload는 상업용 클래스 라이브러리입니다. 요청 프로세스를 구문 분석하는 동안 데이터가 메모리에 저장되므로 더 빠르지 만 더 큰 파일을 업로드 할 때 메모리 오버플로가 발생합니다. Apache Commons FileUpload는 무료 및 오픈 소스 클래스 라이브러리입니다. Struts와 같은 일부 프레임 워크는 Apache Common FileUpload 클래스 라이브러리를 통합하여 파일 업로드를 구현합니다.
그림과 같이 :
코드는 다음과 같습니다.
패키지 com.helloweenvsfei.servlet; import java.io.file; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStream; import java.io.outputStream; import java.io.printwriter; import java.net.urlencoder; java.util.lencoder; import java.io.printwriter; javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.fileupload.dickfileuplof; org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; public class uploadservlet httpservlet {private static final long serialversionuid = 7523024737218333088L; public void doget (httpservletrequest request, httpservletresponse response) servletexception, ioexception {response.setcharacterencoding ( "utf-8"); response.getWriter (). println ( "포스트에서 파일을 업로드하십시오"); } @suppresswarnings ( "확인되지 않은") public void dopost (httpservletrequest 요청, httpservletResponse 응답)는 servletexception, ioexception {file file1 = null, file2 = null을 던졌습니다. 문자열 description1 = null, description2 = null; 응답 .SetchAracterEncoding ( "UTF-8"); Response.setContentType ( "Text/Html"); 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 ( "<link rel = 'stylesheet'type = 'text/css'href = '../css/style.css'>"); out.println ( "<body>"); out.println ( "<div align = center> <br/>"); out.println ( "<fieldset style = 'width : 90%'> <Legend> 파일 업로드 </legend> <br/>"); out.println ( "<div class = 'line'>"); out.println ( "<div align = 'left'class = 'leftdiv'> 업로드 로그 : </div>"); out.println ( "<div align = 'left'class = 'rightdiv'>"); // DiskFileUpload 객체를 사용하여 구문 분석 요청 DiskFileUpload DiskFileUpload = New DiskFileUpload (); 시도 {// 구문 분석 된 결과를 목록 목록에 배치합니다 <fileItem> list = diskfileupload.parserequest (request); out.println ( "모든 파일을 통한 추적 ... <br/>"); // fileItemitem : list)에서 모든 fileItems를 목록을 통해 추적합니다 {if (fileItem.isformfield ()) {// if ( "descripment1".Equals (fileItem.getFieldName ())) {// 파일 이름이 description1 out.println ( "travel to description1 ... <br/>"); description1 = 새 문자열 (fileitem.getString (). getBytes (), "utf-8"); } if ( "description2".equals (fileItem.getFieldName ())) {// 파일이 이름이 description2 Out.println ( "travel to description2 ... <br/>"); description2 = 새 문자열 (fileitem.getString (). getBytes (), "utf-8"); }} else {// file field if ( "file1".equals (fileItem.getFieldName ())) {// 클라이언트 파일 파일 remoteFile = 새 파일 (fileItem.getName (). getBytes (), "utf-8"); out.println ( "File1로 이동 ... <br/>"); out.println ( "클라이언트 파일 위치 :" + remotefile.getabsolutepath () + "<br/>"); // Server-Side 파일, 폴더 업로드 파일에 배치 파일을 배치합니다. file11.getParentFile (). mkdirs (); file1.createnewfile (); // 파일을 작성하고 파일의 파일 내용을 파일 inputStream ins = fileItem.getInputStream ()에 작성합니다. outputStream ous = 새 FileOutputStream (file1); try {byte [] buffer = new Byte [1024]; int len = 0; while ((len = ins.read (buffer))> -1) ous.write (buffer, 0, len); out.println ( "파일 저장" + file1.getabsolutepath () + "<br/>"); } 마침내 {ous.close (); ins.close (); }} if ( "file2".equals (fileItem.getFieldName ())) {// 클라이언트 파일 파일 파일 remoteFile = 새 파일 (new String (fileItem.getName (). getBytes (), "utf-8")); out.println ( "file2로 이동 ... <br/>"); out.println ( "클라이언트 파일 위치 :" + remotefile.getabsolutepath () + "<br/>"); // 서버 측 파일, 폴더 업로드 파일에 넣습니다. 파일 2 = 새 파일 (this.getServletContext (). getRealPath ( "첨부 파일"), remoteFile.getName ()); file2.getParentFile (). mkdirs (); file2.createnewfile (); // 파일을 작성하고 파일의 파일 내용을 파일 inputStream ins = fileItem.getInputStream ()에 작성합니다. outputStream ous = 새 FileOutputStream (file2); try {byte [] buffer = new Byte [1024]; int len = 0; while ((len = ins.read (buffer))> -1) ous.write (buffer, 0, len); out.println ( "파일 저장" + file2.getabsolutepath () + "<br/>"); } 마침내 {ous.close (); ins.close (); }}}} out.println ( "요청 구문 분석이 완료되었습니다"); } catch (fileUploadeXception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); } out.println ( "</div>"); out.println ( "<div align = 'left'class = 'leftdiv'> file1 : </div>"); out.println ( "<div align = 'left'class = 'rightdiv'>"); out.println ( "<a href = '" + request.getContextPath () + "/attly/" + file1.getName () + "'target = _blank>" + file1.getName () + "</a>"); out.println ( "</div>"); out.println ( "</div>"); } if (file2! = null) {out.println ( "<div class = 'line'>"); out.println ( "<div align = 'left'class = 'leftdiv'> file2 : </div>"); out.println ( "<div align = 'left'class = 'rightdiv'>"); out.println ( "<a href = '" + request.getContextPath () + "/attly/" + urlencoder.encode (file2.getName (), "utf-8") + "'target = _blank>" + file2.getName () + "</a>"); out.println ( "</div>"); out.println ( "</div>"); } out.println ( "<div class = 'line'>"); out.println ( "<div align = 'left'class = 'leftdiv'> description1 : </div>"); out.println ( "<div align = 'left'class = 'rightdiv'>"); out.println ( "<div align = 'left'class = 'rightdiv'>"); out.println ( "<div align = 'left'class = 'leftdiv'> description2 : </div>"); out.println ( "<div align = 'left'class = 'rightdiv'>"); out.println (description2); out.println ( "</div>"); out.println ( "</div>"); out.println ( "</fieldset> </div>"); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); }}프로그램 작동 효과는 그림에 나와 있습니다.
이 기사는 "Java 업로드 작업 기술의 요약"으로 편집되었으며 모든 사람들은 배우고 읽을 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.