파일 업로드 및 다운로드
프론트 데스크 :
1. 제출 방법 : post
2. 양식에는 파일 업로드 된 양식 항목이 있습니다. <input type = "file" />
3. 양식 유형을 지정합니다.
기본 유형 : ENCTYPE = "application/x-www-form-urlencoded"
파일 업로드 유형 : 멀티 파트/양식 데이터
fileUpload
파일 업로드 기능의 개발에 일반적으로 사용되며 Apache도 파일 업로드 구성 요소를 제공합니다!
fileUpload 구성 요소 :
1. 소스 코드를 다운로드하십시오
2. 프로젝트에 JAR 파일을 소개합니다
Commons-FileUpload-1.2.1.jar [파일 업로드 구성 요소 코어 JAR 패키지]
Commons-IO-1.4.jar [파일 처리를위한 자수 관련 도구 클래스]
사용:
공개 클래스 업로드가 httpservlet {// 업로드 디렉토리, 업로드 된 리소스 저장, 공개 void doget (httpservletrequest request, httpservletreponse responsk) servletexception, ioexception, ioexception, ioexception, ioexception, ioexception {/************** 파일 업로드 ******************************************* // 1. Factory = New DiskFileItemFactory (); // 2. 파일 생성 핵심 도구 클래스 ServletFileUpload Upload = New ServletFileUpload (Factory); // 1. 단일 파일에 허용되는 최대 크기 설정 : 30Mupload.setfilesizemax (30*1024*1024); // 2. 파일 업로드 양식에 허용되는 전체 크기를 설정하십시오. 80mupload.setsizemax (80*1024*1024); // 3. 업로드 양식의 파일 이름 인코딩을 설정하십시오. // request.setcharacterencoding ( "UTF-8"); UPLOD.SETHEADERENCODING ( "UTF-8"); // 3. 결정 : 현재 양식이 파일 업로드 양식인지 (upload.IsMultipArtContent (request)) {// 4. 요청 된 데이터를 파일 객체로 변환 한 다음 <fileItem> list = upload.parserequest (요청); List) {// 판단 : 정상 텍스트 데이터 if (item.isformfield ()) {// 일반 텍스트 데이터 문자열 fieldName = item.getFieldName (); // 폼 요소 이름 문자열 content = item.getString (); // 형식 요소 이름, 해당 데이터 //item.getString("utf-8 "); 인코딩 System.out.println (FieldName + "" + content);} // 파일 업로드 (파일 스트림) ---> 업로드 디렉토리에 업로드 {// 일반 텍스트 데이터 문자열 필드 이름 = item.getFieldName (); // 형식 요소 이름 문자열 이름 = item.getName (); // 파일 이름 문자열 content = item.getString (); // 형식 요소 이름, 해당 데이터 문자열 유형 = item.getContentType (); // 파일 유형 inputStream in = item.getInputStream (); // 파일 스트림 업로드/** 4. 파일 이름 이름 바꾸기* 다른 사용자의 경우 readMe.txt 파일을 사용하지 않으려면! * 배경 처리 : 사용자에게 고유 한 태그를 추가하십시오!* /// a. 고유 한 태그 문자열 id = uuid.randomuuid (). tostring (); // b를 무작위로 생성합니다. 파일 이름 = id + "#" + name; // 업로드베이스 경로 문자열 경로를 가져옵니다. String 경로 = GetServletContext (). getRealPath ( "/Upload"); // 대상 파일 파일 생성 = 새 파일 (path, name); // 툴 클래스, 파일 업로드 항목 (파일); item.delete (); // System.out.println ();}}} else {System.out.println ( "현재 양식은 파일 업로드 양식, 처리 실패!")에 의해 생성 된 임시 파일을 삭제합니다. ioException, UnSupportedEncodingException {/* request.getParameter ( ""); // get/postrequest.getQueryString (); // get request.getInputStream ()에 의해 제출 된 데이터를 가져옵니다. // post*// ********************에서 제출 한 데이터를 가져옵니다. 수동으로 파일 업로드 양식 데이터를 가져옵니다 **************** /// 1. 폼 데이터 스트림 inputStream in = request.getInputStream (); // 2를 가져옵니다. 스트림 inputStreamReader instream = new inputStreamReader (in, "utf-8"); // 3을 변환합니다. bufferedReader reader = new bufferedReader (instream); // 출력 데이터 문자열 str = null; 응답) servletexception, ioexception {this.doget (요청, 응답);}}사례:
index.jsp
<body> <a href = "$ {pagecontext.request.contextpath} /upload.jsp"> 파일 업로드 </a> <a href = "$ {pagecontext.request.contextpath}/fileservlet? downlist"> 파일 다운로드 </a> </body>upload.jsp
<body> <form name = "frm_test"action = "$ {pagecontext.request.contextpath}/fileservlet? method = upload"method = "post"enctarpe = "multipart/form-data"> <%-<입력 유형 = "hidden"name = "method">-%> username : <input type = "텍스트" "텍스트" <br/> 파일 : <input type = "file"name = "file_img"> <br/> input type = "제출"value = "제출"> </form> </body>fileservlet.java
/*** 프로세스 파일 업로드 및 다운로드*@author jie.yuan **/public class fileservlet는 httpservlet {public void doget (httpservletrequest request, httpservletresponse 응답)을 확장합니다. servletexception, ioexception {// 다른 운영 유형 얻기 문자열 방법 = 요청. ( "업로드".Equals (method)) {// 업로드 업로드 (요청, 응답);} else if ( "downlist".equals (method)) {// 다운로드 목록 다운 목록 (요청, 응답);} else if ( "down".equals (method)) {// 다운로드 (요청, 응답); *** 1./private uplet upport, up -upper] httpservletResponse 응답) servletexception, ioexception {try {// 1. 공장 객체 생성 파일 시합 변형 팩토리 = 새로운 diskfileitemfactory (); // 2. 핵심 도구 클래스 ServletFileUpload upload = new servletfileUpload (factory); // set size limit parameters upload. (10*1024); // 단일 파일 크기 제한 UPLOAD.SETSIZEMAX (50*1024*1024); // 총 파일 크기 제한 업로드 .SetHeAderEncoding ( "UTF-8"); // 중국어 파일 인코딩 // 판단 if (upload.ismultipartContent (request)) {// 3. 요청 데이터 변환 수집 목록으로 변환 <FileItem> 목록 <PileItem> list = upload.parserequest (request); // traversal for (list) {// judgment : item.isfortfield (get string the mare get the marge the mare get the marge) value = item.getString (); system.out.println (value);} // 파일 양식 항목 {/************ 파일 업로드 **************** /// a. 파일 이름 문자열 이름 = item.getName (); // --- 파일 이름 업로드 문제를 처리합니다 --- // a1. 고유 한 마크 문자열 id = uuid.randomuuid (). toString (); // a2를 가져옵니다. 스플 라이스 파일 이름 이름 = id + "#" + 이름; // b. 업로드 디렉토리 문자열 basepath = getServletContext (). getRealPath ( "/upload"); // c. 업로드 할 파일 객체를 작성 파일 = 새 파일 (Basepath, name); // d. 업로드 item.write (file); item.delete (); // 구성 요소가 실행될 때 생성 된 임시 파일을 삭제합니다}}}}}} catch (예외 e) {e.printstacktrace ();}}/*** 2. 다운로드 목록을 입력하십시오*/private void downlist (httpservletrequest 요청) 디렉토리를 업로드 한 다음 저장하십시오. down.jsp 목록으로 이동하여 // 1을 표시하십시오. 맵 수집 맵을 초기화 <고유 한 태그, 짧은 파일 이름을 포함하는 파일 이름>; map <string, string> filenames = new Hashmap <String, String> (); // 2. string bathpath = getServletContext (). getRealPath ( "/upload"); // 디렉토리 파일 파일 = 새 파일 (bathpath); // 디렉토리의 모든 파일 이름 문자열 목록 [] = file.list (); // 트래버스, acappulate if (list && list.l 길이> 0) {int i = 0); i ++) {// full name string filename = list [i]; // 짧은 이름 string shortname = filename.substring (filename.lastindexof ( "#"))+1); // acapulation filenames.put (filename, shortname);}} // 3. 요청 도메인 요청 .setattribute ( "filenames"); request.getRequestDisPatcher ( "/downlist.jsp"). Forward (요청, 응답);}/*** 3. 다운로드 핸들*/private void down (httpservletrequest request, httpservletreponse responsk)은 servletexception, ioexception {// url jourden at append 데이터를 얻는다.) request.getParameter ( "filename"); filename = new String (filename.getBytes ( "iso8859-1"), "utf-8"); // 업로드 디렉토리 경로 얻기 문자열 basepath = getServletcontext (). 파일 이름이 중국인 인 경우 URL 인코딩을 수행 해야하는 경우 filename = urlencoder.encode (filename, "utf-8"); // 다운로드에 대한 응답 헤더를 설정합니다 ( "content-disposition", "첨부 파일; filename =" + filename); // get repasion by out outputstream out = response. len = -1; while ((len = in.read (b))! = -1) {out.write (b, 0, len);} // close.close (); in.close ();} public void dopost (httpservletrequest request, httpservletresponse 응답) servletexception, ioexception {this.doget (요청, 응답);}}}}우편 개발
준비 작업, 환경 구성 :
1. 메일 서버를 로컬로 구축하십시오
Easymail Server, eyoumailserversetup.exe
2. 새 이메일 계정을 만듭니다
Zhang San은 Li Si에게 이메일을 보냈습니다.
Step 1:
새 도메인 이름 만들기 : 도구, 서버 설정, 단일 도메인 이름 상자에 itcast.com을 입력하십시오.
Step 2:
새 이메일 계정을 작성하십시오 : [email protected]
3. Foxmail을 설치하십시오
이메일 보내기 서버 (SMTP) : LocalHost 25를 구성하십시오
이메일 수신 서버 (POP3) : LocalHost 110
새 계정을 만들면 이메일을받을 수 있습니다!
알아채다
알아채다
웹 프로젝트 인 경우 Javaee가 이메일 기능을 제공하기 때문에 문제가있을 수 있습니다!
우리는 우리 자신의 mail.jar 파일 함수를 사용해야합니다! Javaee에서 메일 패키지를 삭제해야합니다!
사용:
Javamail 개발의 경우 먼저 JAR 파일을 소개합니다.
activation.jar [JDK1.6 이상을 사용할 수있는 경우이 JAR 파일을 사용할 수 없으면] mail.jar [이메일로 코어 패키지 보내기]/*** 1. 일반 이메일 보내기*@author jie.yuan **/public class app_sendmail {@testpublic void testsend () 예외를 {// 0. 메일 매개 변수 속성 properties = new Properties (); prop.put ( "mail.transport.protocol", "smtp"); // 프로토콜 prop.put ( "mail.smtp.host", "localhost")을 지정합니다. // 호스트 stmp.qq.comprop.put ( "mail.smtp.port", 25); // port prop.put ( "mail.smtp.auth", "true"); // 사용자 비밀번호 인증 prop.put ( "mail.debug", "true"); // 디버그 모드 // 1. 메일 세션 세션 세션을 만듭니다. 세션. 세션 .getDefaultInstance (prop); // 2. 메일 바디 객체를 만듭니다 (전체 이메일 객체) mimemessage message = new Mimemessage (세션); // 3. 메일 바디 매개 변수 설정 : //3.1 Title Message.SetSubject ( "My First Email"); // 3.2 이메일 보내기 시간 메시지 보내기 메시지. InternetAddress ( "[email protected]")); // 3.5 Content Message.Settext ( "안녕하세요, 성공적으로 전송되었습니다! 텍스트 ..."); // 간단한 일반 텍스트 이메일 메시지 .SeveChanges (); // 이메일 저장 (선택 사항) // 4. 전송 전송을 보내십시오 = session.gettransport (); trans.connect ( "zhangsan", "888"); // mail을 trans.sendmessage로 보내기 (메시지, message.getallrecipients ()); trans.close ();}}사진과 함께
/*** 이미지 리소스가 포함 된 이메일*@Author jie.yuan **/public class app_2sendwithimg {// 초기화 매개 변수 개인 정적 속성 proper; // sender private static internetaddress sendman = null; static {proper = new Properties ( "mail.transport.protocol", "smtp"); // 프로토콜 prop.put ( "mail.smtp.host", "localhost")을 지정합니다. // 호스트 stmp.qq.comprop.put ( "mail.smtp.port", 25); // 프로토콜 prop.put ( "mail.smtp.port", 25)을 지정합니다. // 프로토콜 prop.put ( "mail.smtp.port", "localhost")을 지정합니다. // 호스트 stmp.qq.comprop.put ( "mail.smtp.port", 25); // port prop.put ( "mail.smtp.auth", "true"); // 사용자 비밀번호 인증 prop.put ( "mail.debug", "true"); // 디버그 모드 try {sendman = new InternetAddress ( "[email protected]");} catch (jesdrexception e) {새로운 runtimeexception (e);}}@testpublic void testsend () 예외 {// 1. 메일 세션 세션 = session을 만듭니다. mimemessage (세션); // 3. 매개 변수 설정 : 제목, 발신자, 수신자, 시간 보내기, 내용 메시지 .setSubject ( "그림 메일"); Message.SetSender (Sendman); message.setRecipient (RecepitientType.to, New InternetAddress ( "[email protected]")); Message.SetSentDate (new date ());/********************** 이메일 내용 설정 : 다기능 사용자 이메일 (관련) ********************** /// 4.1 다기능 이메일 블록 MimemultIpart 관련 = 새로운 Mimemultipart ( "관련"; // 왼쪽 + resource의 텍스트에 대한 텍스트의 텍스트를 구축하십시오. content = new MimeBodyPart (); MimeBodyPart resource = new MimeBodyPart (); // 특정 컨텐츠 설정 : a. Resource (Picture) String Filepath = App_2SendwithImg.class.getResource ( "8.jpg"). getPath (); DataSource ds = new FileDataSource (새 파일 (filepath)); DataHandler handler = new Datahandler (DS); Resource.setDataHandler (resource.setDataHandler); // 리소스 이름을 설정하고 참조 외국 키를 참조하십시오. // 특정 내용을 설정하십시오. b. text content.setContent ( "<img src = 'cid : 8.jpg'/> ok!", "text/html; charset = utf-8"); 관련 .addodypart (content); antaint.addbodypart (resource);/********* 4.3 전자 메일에 내장형 이메일을 추가 ******** 5. 5. session.getTransport (); trans.connect ( "Zhangsan", "888"); trans.sendMessage (메시지, message.getallrecipients ()); trans.close ();}}그림 + 첨부 파일
/*** 3. 이미지 리소스 및 첨부 파일이 포함 된 이메일*@author jie.yuan **/public class app_3imgandatta {// 초기화 매개 변수 비공개 정적 속성 prop; // sender private static internetaddress sendman = null; static {prop = new Properties (); prop.put ( "mail.transport.protocol", "); // 프로토콜 prop.put ( "mail.smtp.host", "localhost")을 지정합니다. // 호스트 stmp.qq.comprop.put ( "mail.smtp.port", 25); // port prop.put ( "mail.smtp.auth", "true"); // 사용자 비밀번호 인증 prop.put ( "mail.debug", "true"); // 디버그 모드 try {sendman = new InternetAddress ( "[email protected]");} catch (jesdrexception e) {새로운 runtimeexception (e);}}@testpublic void testsend () 예외 {// 1. 메일 세션 세션 = session을 만듭니다. mimemessage (세션); // 3. 매개 변수 설정 : 제목, 발신자, 수신자, 시간 보내기, 내용 메시지. Message.SetSender (Sendman); message.setRecipient (RecepitientType.to, New InternetAddress ( "[email protected]")); Message.SetSentDate (new date ());/** 첨부 파일 (그림)*// 메일 개발*// 총 메일 블록 구성 MIMEMULTIPART MIXED = NEW MIMEMULTIPART ( "MIXED"); //-> TOTAL MAIL IS FAST, MITERTENT (Mixed); // 왼쪽 : (Text + image Bodypart) MimeBodyPart (New MimebodyPart); right = new MimebodyPart (); // 총 메일 블록 mixed.addbodyPart (왼쪽)로 설정; mixed.addbodypart (오른쪽);/******* 첨부 파일 **********/String Att_path = this.getClass (). getResource ( "a.docx"). getPath (); dataSource attr_ds = new FileDatAsource (새 파일 (attr_path)); datahandler attr_handler = new Datahandler (Att_ds); right.setdatahandler (attr_handler); right.setfilename ( "a.docx");/**************************** 이메일 컨텐츠 설정 : 다기능 사용자 이메일 (관련) ******************** // 4.1 다기능 이메일 빌드 mimmultipart (new Mimmultipart); ---> 왼쪽으로 설정하십시오 .SetContent (relate); // 4.2 다기능 메일 블록 내용을 빌드 왼쪽의 텍스트 + 오른쪽의 텍스트 + 이미지 자원 컨텐츠 = new MimeBodyPart (); MimeBodyPart Resource = new MimeBodyPart (); // 세트 특정 콘텐츠 : a. Resource (Picture) String Filepath = App_3imgandatta.class.getResource ( "8.jpg"). getPath (); DataSource ds = new FileDataSource (새 파일 (filepath)); datahandler handler = new Datahandler (DS); Resource.setDataHandler (hroughs); // 리소스 이름을 설정하고 참조 외국 키를 참조하십시오. // 특정 내용을 설정하십시오. b. text content.setContent ( "<img src = 'cid : 8.jpg'/> ok!", "text/html; charset = utf-8"); 관련 .addodypart (content); 관련 .addbodypart (resource); // 5. sendtransport = session.ettransport (); trans.connect ( "Zhangsan", "Zhangsan", "888"); trans.sendMessage (메시지, message.getallrecipients ()); trans.close ();}}위의 것은 Java 파일을 업로드하고 다운로드하고 소개 된 이메일을 보내기위한 예제 코드입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!