파일 업로드는 웹 응용 프로그램에서 매우 일반적입니다. 이제 서블릿을 기반으로 파일 업로드를 소개하겠습니다. struts2를 기반으로 파일 업로드를 볼 수 있습니다.
페이지 사이드 코드 :
<%@ page language = "java"import = "java.util.*"pageEncoding = "gbk"%> <! doctype html public "-// w3c // dtd html 4.01 전환 // en"> <html> <head> <title> register </head> <retory> <양식 name = form1 "onsubmit =" on_submit () "action ="retherservlet "method ="post "enctype ="multipart /form-data "> <input type ="text "name ="uname1 "id ="password " /> <input type ="text "name ="uname2 "id ="uname2 " /> <input type ="password "password1"id = "id ="input type = "password2". id = "password"/> <input type = "radio"value = "male"checked = "checked"name = "sex"/> male <input type = "radio"value = "female"name = "sex"/> female <input type = "text"name = "email"value = "id ="login "/> <br/> <br/> <br/> <nput type ="file = "id" "id" "id" "id" 이름 = "제출"value = "완료 등록"/> </form> </body> </html>
여기서 주목해야 할 것은 파일에 업로드 된 양식이 EncType = "multipart/form-data"여야한다는 것입니다. 여기서 우리는 Ajax 상호 작용없이 배경과 직접 상호 작용합니다. Ajax를 사용해야하는 경우 http://www.cnblogs.com/shenliang123/category/372520.html을 참조하십시오.
Servlet의 코드 구현을 계속 살펴 보겠습니다.
package com.xidian.bbs.servlet; import java.io.ioexception; import java.io.printwriter; import java.net.inetAddress; import java.sql.connection; import java.sql.resultset; import java.sql.statement; javax.servletexmence; javax.servlet.http.httpservlet; import javax.servlet.http.htttp.httpervletrequest; import javax.servlet.http.http.http.httpervletresponse; import javax.servlet.jsp.jspfactory; import javax.servlet.jsp.pagecontext; com.jspsmart.upload.*; import com.xidian.bbs.bean.bean; import com.xidian.bbs.bean.registerbean; import com.xidian.bbs.util.dbaccess; import com.xidian.bbs.util.iptimeStamp; @suppresswarnings ( "Serial") doget (httpservletrequest request, httpservletresponse response) servletexception, ioexception {response.setContentType ( "text/html"); 응답 .SetchAracterEncoding ( "GBK"); request.setcharacterencoding ( "gbk"); SmartUpload Smart = New SmartUpload (); try {// pagecontext는 JSP의 내장 객체입니다. 서블릿에서 직접 사용할 수 없으며 일부 처리가 필요합니다. jspfactory _jspxFactory = null; pagecontext pagecontext = null; _jspxFactory = jspfactory.getDefaultFactory (); pagecontext = _jspxFactory.getPageContext (this, request, response, "", true, 8192, true); smart.initialize (pagecontext); // 업로드 작업 초기화 smart.upload (); iptimestamp its = new iptimestamp (inetaddress.getlocalhost (). gethostaddress ()); // request.getRemoteaddr ()는 사용자의 IP 주소 // system.out.println을 가져옵니다 ( "IP는"+inetAddress.getLocalHost (). GetHostAddress (); // 파일의 배치 업로드를 구현하려면 for loop and getfile (0)에서 getfile (0)에서 i to i to i to string ext = smart.getFiles (). getFile (0) .getFileExt (); // 파일을 얻기위한 확장자, getFile (0)은 getFile (0)은 getFile (0)입니다. //system.out.println(" 획득 한 파일 이름은 "+filename); //this.getServletContext().getRealPath("/ ") TomCat 디렉토리를 얻으려면 업로드 폴더에 배치됩니다. java.io.file.separator는 안전한 작동 // String realPath = ""; //this.getServletContext().getRealPath("/")/smart.getFiles (). getFile (0) .SaVeas ( "/headupload"+java.io.file.separator+filename); String RealPath = "Headupload/"+filename+""; // // 이전 양식 양식이 캡슐화되었으므로 request.getParameter ()를 사용하여 양식 매개 변수를 가져 오기 위해 문자열을 얻을 수 없습니다. // 닉네임 string upass1 = smart.getRequest (). getParameter ( "password1"); 문자열 sex = smart.getRequest (). getParameter ( "섹스"); 문자열 uname2 = smart.getRequest (). getParameter ( "uname2"); // 사용자 이름 문자열 이메일 = smart.getRequest (). getParameter ( "이메일"); printwriter out = response.getwriter (); // 다음은 지속성 레이어 작업입니다. . . . . . . . . . } 보호 된 void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {doget (요청, 응답); }}위에 사용 된 IP+Timestamp 클래스 iptimestamp는 파일을 이름 바꾸립니다.
파일 및 기타 작업을 업로드 할 때 파일 이름이 상충되는 것을 방지하기 위해 이름 변경 작업을 수행합니다. 다음은 IP+ 타임 스탬프를 구현하는 이름 지정입니다.
방금 코드를 업로드했습니다. 할 말이 없습니다. 구현은 매우 간단하지만 실용적입니다.
package com.xidian.bbs.util; import java.text.simpledateformat; import java.util.date; import java.util.random; public class iptimestamp {private simpledateformat sim = null; // 시간 개인 문자열 ip = null; public iptimestamp () {} public iptimestamp (String IP) {this.ip = ip; } public String getiptimerand () {StringBuffer sbf = new StringBuffer (); if (this.ip! = null) {string a [] = this.ip.split ( "//."); // 포인트에 따라 IP 주소를 분할하지만 (int i = 0; i <a.length; i ++) {sbf.append (this.addzero (a [i], 3)); // 제로 보상 방법을 호출하고 3 자리 미만의 각 IP가 자동으로 3 자리로 보충됩니다} sbf.append (this.getTimestamp ()); // 이것을 사용하여 외부 메소드를 호출하려면 random random = new random (); // (int i = 0; i <3; i ++)에 대한 랜덤 숫자 생성 {// 3 자리 랜덤 번호 생성 sbf.append (random.nextInt (10)); // 각 임의 숫자는 10}}} return sbf.tostring (); } @SuppressWarnings ( "Unused") private String getDate () {// 날짜와 시간에 관한 // this.sim = new SimpledateFormat ( "yyyy-mm-dd hh : mm : ss.sss"); reture this.sim.format (new date ()); } private string getTimestamp () {// return timestamp this.sim = new SimpledateFormat ( "yyyymmddhhmmssss"); reture this.sim.format (new date ()); } private string addzero (String str, int len) {// 자동 제로 보상 메소드, 매개 변수는 지정된 문자열 및 길이 StringBuffer s = new StringBuffer (); S.append (str); while (s.length () <len) {s.insert (0, "0"); // 제로 위치에서 제로 보상 작업을 완료} return s.toString (); } // test public static void main (string [] ary) {iptimestamp iptimestamp = new iptimestamp ( "172.168.3.222"); // 매개 변수로 생성자를 호출 System.out.println (iptimestamp.getiptimerand ()); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.