먼저 파일의 업로드를 소개하겠습니다
엔티티 클래스
java.sql.timestamp import; / ** * * @described 파일 업로드 엔티티 클래스 */ public class upfile {private string id; // id 기본 키 무작위로 비공개 문자열 uuidname을 생성합니다. // UUID 이름 개인 문자열 filename; // 파일 이름 개인 문자열 savepath; // 경로 저장 비공개 타임 스탬프 업로드 타임; // 시간을 업로드 개인 문자열 설명; // 파일 설명 개인 문자열 사용자 이름; // username public upfile () {super (); } public upfile (문자열 ID, 문자열 UUIDNAME, 문자열 파일 이름, String SavePath, Timestamp UploadTime, String Description, String username) {super (); this.id = id; this.uuidname = uuidname; this.filename = filename; this.savepath = savepath; this.uploadtime = 업로드 타임; this.description = 설명; this.username = username; } public String getDescription () {return description; } public String getFileName () {return filename; } public String getId () {return id; } public String getSavePath () {return savepath; } public timestamp getUploadtime () {return ubloadtime; } public String getUserName () {return username; } public String getUuidName () {return uuidName; } public void setDescription (문자열 설명) {this.Description = 설명; } public void setfilename (String filename) {this.filename = filename; } public void setId (String id) {this.id = id; } public void setSavePath (String SavePath) {this.savePath = SavePath; } public void setuploadtime (timestamp uploadtime) {this.uploadtime = 업로드 타임; } public void setusername (String username) {this.username = username; } public void setuuidName (String UUIDName) {this.uuidName = uuidName; }}페이지
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <%string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerport ()+path+"/"; %> <! docType html public "-// w3c // dtd html 4.01 전환 // en"> <html> <head> <head> <base href = "<%= basepath%>"> <title> 내 jsp 'upload.jsp'시작 페이지 </title> <meta http-equiv = "no-cache" "no-cache" " http-equiv = "Cache-control"content = "no-cache"> <meta http-equiv = "chewors"content = "0"> <meta http-equiv = "keyword ="keyword1, keyword2, keyword2, keyword3 "> <meta http-equiv ="descript "> <" "rel rel rele"> type = "text/css"href = "styles.css">->-> </head> <hod> <h1> 파일 업로드 </h1> <form action = "$ {pagecontext.request.contextpath}/upload"method = "post"acttart/form-data "> <tr> <td> <td> uploy <td> <입력 유형 = "text"name = "username"/> </td> </tr> <tr> <td> 파일 업로드 : </td> <td> <input type = "file"= "file"/> </td> </td> <td> 설명 : </td> <Textarea Rows = "5" "50" 이름 = "description"> </textArea> </td> </tr> <td> <td> <input type = "value ="value = "업로드 시작"/> </td> </tr> </table> <div> $ {msg} </div> <a href = "$ {pagecontext.request.context.context.context. </body> </html> 서틀
import java.io.ioexception; javax.servlet.servletexception import; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.fileupload.fileuploadbase.filesizelimitexeceededException; import org.apache.commons.fileupload.fileuploadbase.sizelimitexeceededException; import org.apache.commons.fileupload.servlet.servletfileupload; com.isheima.domain.upfile import; import com.isheima.exception.myexception; com.isheima.service.upfileservice import; com.isheima.service.impl.upfileserviceimpl import; import com.isheima.tils.webuntil; public class uploadfileservlet는 httpservlet {public void doget (httpservletrequest 요청, httpservletresponse 응답)을 servletexception, ioexception {dopost (요청, 응답); } public void dopost (httpservletrequest 요청, httpservletrequest 응답)는 servletexception, ioexception {// 양식이 여러 부분으로 구성되어 있는지 판단합니다 (! servletfileupload.ismultipartContent (요청)) {request.setattribute ( "msg", "settepte") request.getRequestDispatcher ( "/upload.jsp"). FORMPENT (요청, 응답); 반품 ; } // 다중 부문 인 경우 파일 업로드 객체를 반환하기 위해 다중 부분으로 가져 와서 트래버스를 반환합니다. upfileservice upfileservice = 새로운 upfileserviceimpl (); 부울 플래그 = upfileservice.add (upfile); if (flag) {request.setAttribute ( "msg", "Upload 성공"); request.getRequestDispatcher ( "/upload.jsp"). FORMPENT (요청, 응답); 반품 ; } else {request.setAttribute ( "msg", "업로드 실패, 다시 시도하십시오"); request.getRequestDispatcher ( "/upload.jsp"). FORMPENT (요청, 응답); 반품 ; }} catch (filesizelimitexeceedeDexception e) {e.printstacktrace (); request.setAttribute ( "msg", "단일 파일 크기, 최대 한계를 초과하는 단일 파일 크기"); request.getRequestDispatcher ( "/upload.jsp"). FORMPENT (요청, 응답); 반품 ; } catch (sizelimitexeceededException e) {e.printstacktrace (); request.setattribute ( "msg", "총 파일 크기, 최대 한계를 초과하는"); request.getRequestDispatcher ( "/upload.jsp"). FORMPENT (요청, 응답); 반품 ; }}}도구
import java.io.file; import java.io.filenotfoundException; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputstream; import java.io.outputStream; import java.io.usupportedencodingException; java.util.arraylist 가져 오기; Java.util.list 가져 오기; java.util.uuid import; import javax.servlet.http.httpservletrequest; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadbase; import org.apache.commons.fileupload.fileuploadbase.filesizelimitexeceededException; 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; com.isheima.domain.upfile import; import com.isheima.exception.myexception; / ** * 파일 업로드 도구 클래스 * @describe todo */ public class webuntil {/ ** * 파일 업로드 메소드 * @param 요청 * @return upfile 객체를 반환 * @throws filesizelimitexceection * @throws sizelimitexceerts ioexception */ public upfile upfile upfile upfile upfile upfile upfile filesizelimitexceedEdexception, sizelimitexceededEdexception {upfile upfile = new upfile (); ArrayList <string> filEList = initList (); 시도 {// 디스크 파일 가져 오기 객체 공장 diskfileitemfactory factory = new diskfileitemfactory (); 문자열 tmp = request.getSession (). getServletContext (). getRealPath ( "/tmp"); System.out.println (TMP); // 팩토리 초기화 setFactory (Factory, TMP); // 파일 업로드 Parser ServletFileUpload 업로드 = New ServletFileUpload (Factory); // Parser setUpload 초기화 (업로드); // 파일 목록 가져 오기 <fileItem> list = upload.parserequest (요청); // (fileItem 항목 : list) {// 일반적인 양식 객체인지 판단 if (items.isformfield ()) {// 업로드 형식의 이름을 얻습니다. string fieldName = items.getFieldName (); // 값 문자열 fieldValue = items.getString ( "UTF-8"); // if ( "username".equals (fieldName)) {// upfile.setusername (fieldValue); } else if ( "describ" }} else {// 파일을 업로드 할 준비가되어 있습니까? // 파일 이름 string filename = items.getName (); // 다른 브라우저로 인해 얻은 파일 이름의 차이를 처리합니다 int index = filename.lastIndexof ( "//"); if (index! = -1) {filename = filename.substring (index+1); } // 랜덤 파일 이름 생성 문자열 uuidname = generateFilename (filename); // 업로드 된 파일 경로 문자열 savepath = requestSession (). getServletContext (). getRealPath ( "/web-inf/ubload"); // 요청 객체에서 입력 스트림을 가져옵니다. inputStream in = items.getInputStream (); // 파일을 깨고 다른 경로에 저장하고 경로를 찾으십시오. SavePath = GeneraterAndomDir (SavePath, uuidName); // uploadfile 파일을 복사합니다 (in, savepath, uuidname); 문자열 id = uuid.randomuuid (). toString (); upfile.setid (id); upfile.setsavepath (savepath); upfile.setuuidname (uuidname); upfile.setfilename (filename); // CHELE CACHE ITIMS.DELETE (); }}} catch (fileUploadBase.FileSizelimiteXeceedEdexception e) {// 예외 던지기 e; } catch (fileUploadBase.SizelimiteXeceedEdException e) {// 예외적 인 e; } catch (fileUploadeXception e) {e.printstacktrace (); } catch (UnsupportedEncodingException e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); } catch (예외 e) {e.printstacktrace (); } rack upfile; } / *** 파일 목록 초기화* @return* / private static arraylist <string> initList () {ArrayList <string> list = new ArrayList <string> (); list.add ( ". jpg"); list.add ( ". rar"); list.add ( ". txt"); list.add ( ". png"); 반환 목록; } /*** 파일 복사* @param에서 @param의 입력 스트림* @param savepath save path* @param uuidname 파일 이름* /private static void uploadfile (inputstream in, string savepath, string uuidname) {// 파일 파일 get file (savepath, uuidname); outputStream out = null; {int len = 0; 바이트 [] buf = 새로운 바이트 [1024]; // 출력 스트림을 가져옵니다 = 새 FileOutputStream (파일); while ((len = in.read (buf))! = -1) {out.write (buf, 0, len); }} catch (filenotfoundException e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); } 마침내 {try {in.close (); } catch (ioexception e) {e.printstacktrace (); } try {out.close (); } catch (ioexception e) {e.printstacktrace (); }}} /*** 임의의 저장 경로 생성* @param savepath save path* @param uuidname 생성 된 uuid 이름* @return* 완료* /private static string generaterandomdir (string savepath, string uuidname) {// hashcode system.out.println ( "+save"); system.out.println ( "uuidname"+uuidname); int hashcode = uuidname.hashcode (); // 컨테이너 stringBuilder sb = new StringBuilder (); while (hashcode> 0) {// int 15 int tmp = hashcode & 0xf; sb.append ( "/"); sb.append (tmp+""); 해시 코드 = 해시 코드 >> 4; } // 새 경로 문자열 path = savepath+sb.toString (); System.out.println ( "Path"+Path); 파일 = 새 파일 (Path); // 경로가 존재하는지 (! file.exists ()) {// file.mkdirs (); } // 경로 저장 경로 반환 경로를 반환합니다. } / *** 새 파일 이름을 생성* @param uuidname random id name* @param filename 원본 이름* @return* / private static string generatefilename (String filename) {string uuidname = uuid.randomuuid (). toString (); return uuidname.replace ( "-", "") .toString ()+"_"+filename; } / *** 초기화 파서* @param 업로드* / private static void setupload (servletfileupload upload) {// 문자 인코딩 업로드를 설정합니다. // 파일 크기를 설정합니다. // 총 파일 크기를 설정합니다 .SetSizEmax (1024*1024*50); // Progress LisperSListener (new ProgressListener () {public void update (long pbytesread, long pcontentlength, int pitems) {system.out.println ( "+pbytesread+", 총 : "+pcontentlength+", "+pitems+"); @param tmp 버퍼 디렉토리*/ 개인 정적 void setfactory (diskfileitemfactory factory, string tmp) {/// setsizethreshold (1024*1024); 두 파일을 다운로드하십시오
서틀
public class downupfileservlet는 httpservlet {public void doget (httpservletrequest request, httpservletresponse 응답)을 servletexception, ioexception {dopost (요청, 응답); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {// id string id = request.getParameter ( "id"); // 비즈니스 계층의 인터페이스 Upfileservice upfileservice = new Upfileserviceimpl (); // id upfile upfile = upfileservice.findupfilebyid (id)를 기반 으로이 객체를 찾으십시오. if (upfile == null) {return; } // 파일의 실제 이름을 가져옵니다. string filename = upfile.getfilename (); // 파일 이름에 중국어가있는 경우 트랜스 코드가 필요합니다. 그렇지 않으면 파일 이름 filename = urlencoder.encode (filename, "utf-8")가 없습니다. // 변경 이름 문자열 uuidName = upfile.getUuidName (); // 경로 저장 문자열 savepath = upfile.getSavePath (); 파일 = 새 파일 (savepath, uuidname); // 파일이 존재하는지 (! file.exists ()) {request.setAttribute ( "msg", "다운로드 된 파일이 만료 됨"); request.getRequestDispatcher ( "/index"). FORMPER (요청, 응답); 반품; } // 파일 설정 응답 응답 헤더 정보 응답을 설정합니다 .SetHeader ( "Content-Disposition", "attachement; filename ="+filename); // IO 스트림을 사용하여 inputStream in = new FileInputStream (파일)을 출력합니다. servletoutputStream out = response.getOutputStream (); int len = 0; 바이트 [] buf = 새로운 바이트 [1024]; while ((len = in.read (buf))! = -1) {out.write (buf, 0, len); } in.close (); }}데이터 베이스
데이터베이스 생성 upload_download_exercise를 만듭니다. upload_download_exercise를 사용하십시오. 테이블 업 파일 (id varchar (100), // UUID를 사용하여 UUIDNAME VARCHAR (255), // uUID를 생성하여 원본 파일 이름 filename varchar (100), // 실제 파일 이름 savepath varchar (255), // 경로를 업로드 타임 시간 설명 varchar (255), // username varchar (10) Uploader (10) upload time description varchar (10);
위의 내용은 Commos-FileUpload를 사용하여 파일 업로드 및 다운로드를 달성하는 Java의 관련 컨텐츠입니다. 모든 사람에게 도움이되기를 바랍니다.