이전 기사 옆 :
2. 파일 업로드 및 다운로드
Struts2, Page JSP- 구성 파일 Struts2.xml- 및 Action Class Action에 의해 개발 된 세 가지 트릭
파일 업로드 전제 조건 :
양식 양식의 방법은 게시해야합니다
양식 양식의 ENCTYPE는 멀티 파트/양식 데이터 여야합니다
유형 = "파일"의 업로드 입력 필드 제공
Struts에 대한 일부 규칙은 파일 업로드를 지원합니다
1. 단일 파일 업로드
개발 단계 :
1) Commons-FileUpload-1.2.1.jar 및 Commons-IO-1.3.2.jar를 웹 -INF/lib 아래에 추가하십시오. 이 두 파일은 http://commons.apache.org/에서 다운로드 할 수 있습니다.
2) 2 단계 : upfile.jsp를 작성하고 양식 테이블의 Enctype를 다음과 같이 "multipart/form-data"로 설정하십시오.
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <%@ taglib uri = "/struts-tags"prefix = "s"%> <body> <s : actionerror/<hr/> <s : fielderror> </s : fielderror> <양식 action = "$ {pagecontext.request.contextpath} /upload1.action"method = "post"encType = "post"encType = "multipart/form-data"> <! <! <input type = <input type = "text"name = "username"/> <br/ 아름다운 사진 : <input type = "subj"photo ""in type = "photo". 값 = "업로드"/> </form> </body>오류 페이지 error.jsp를 쓰십시오
<body> 서버가 바쁘다. 잠시 후 다시 시도하십시오. </body>
성공 .JSP
<body> 성공적으로 업로드 </body>
3) write uploadaction1 클래스 : 액션 클래스에 속성을 추가하고 속성은 파일 필드의 이름에 해당합니다.
패키지 com.ithema.actions; import java.io.file; import java.io.ioexception; import org.apache.commons.io.fileutils; import org.apache.struts2.servletactioncontext; import com.opensymphony.xworksupport; // 파일 업로드 : Private Uppport {Private uppport {private string orerame; 개인 파일 사진; // 양식의 업로드 필드 이름과 일치합니다. 유형은 파일 유형 개인 문자열 Photofilename; // 파일 이름 PRIVATE STRNET PHOTOCONTENTTYPE; // 파일을 업로드 파일 MIME 유형 // getter and setter 메소드 public String upload () {system.out.println (photofilename+":"+photocontentType); // 일반 필드 : System.out.println (사용자 이름); // 필드 업로드 : 폴더에 업로드합니다. 응용 프로그램의 이미지 디렉토리 문자열 realpath = servletactionContext.getServletContext (). getRealPath ( "/images")에 저장; 파일 디렉토리 = 새 파일 (realPath); if (! directory.exists ()) {drierce.mkdirs (); } try {fileUtils.copyFile (사진, 새 파일 (directory, photofilename)); 반환 성공; } catch (ioexception e) {e.printstacktrace (); 반환 오류; }}}struts.xml 파일에 다음 구성을 추가하십시오
<action name = "upload1"method = "upload"> <interceptor-ref name = "defaultstack"> <param name = "fileUpload.allowedTypes"> im <culd> /success.jsp </result> <result name = "error">/error "> jsp </result> <result name ="input ">/index.jsp </result> </action>
원칙 분석 :
에이. FileUpload 인터셉터는 파일 업로드 작업을 처리 할 책임이 있습니다. Default DefaultStack 인터셉터 스택의 멤버입니다. 인터셉터에는 설정할 수있는 3 가지 속성이 있습니다.
• 최대 규모 : 업로드 된 파일의 최대 길이 (바이트) 기본값은 2MB입니다.
• alludtypes : 쉼표로 분리 된 파일 업로드를 허용하는 유형.
• 허용 xtensions : 파일 확장을 업로드 할 수 있습니다. 이 3 가지 속성은 각 확장자를 구분하여 struts.xml 파일로 덮어 쓸 수 있습니다.
비. 크기를 초과하거나 불법적으로 파일을 업로드하면 오류가 발생합니다 (입력보기로 바꾸십시오)
통과하다:
<S : ActionError/> <S : Feilderror/> 팁 오류 메시지를 표시합니다
기음. 중국어 버전으로 오류 메시지 프롬프트 변경 : 국제 메시지 리소스 파일의 도움으로
글로벌 기본 매개 변수를 구성하여 오류가 발생하는 경우 글로벌 메시지 리소스 파일을 사용하는 것이 가장 좋습니다.
struts2-core-**. 키 값을 비교하여 해당 값을 덮어 쓰십시오.
구성은 다음과 같습니다.
struts.messages.error.uploading = 오류 업로드 : {0}
struts.messages.error.file.too.large = 너무 큰 파일 : {0} "{1}" "{2}"{3}
struts.messages.error.content.type.not.allowed = content-type 허용 : {0} "{1}" "{2}"{3}
struts.messages.error.file.extension.not.
{0} : <input type = "file"name = "uploadImage"에서 이름 속성의 값
{1} : 업로드 된 파일의 실제 이름입니다
{2} : 임시 디렉토리에 저장된 업로드 파일의 이름
{3} : 업로드 된 파일의 유형 (struts.messages.error.file.too.large의 경우 업로드 된 파일의 크기)
소스 코드 :
오류를 표시하는 리소스 파일의 정보 수정
1 단계 : FileUploadMessage.Properties와 같은 새 리소스 파일 생성 SRC 아래에 배치하여 리소스 파일에 다음 정보를 추가하십시오.
struts.messages.error.uploading = 업로드 오류 : {0}
struts.messages.error.file.too.large = 파일 업로드 파일은 너무 큽니다 : {0} "{1}" "{2}"{3}
struts.messages.error.content.type.not.allowed = 업로드 된 파일의 유형은 허용되지 않습니다 : {0} "{1}" "{2}"{3}
struts.messages.error.file.extension.not.
2 단계 : struts.xml 파일에 리소스 파일을로드합니다.
<!-파일 업로드에 대한 오류 정보에 대한 리소스 파일 구성->
<constant name = "struts.custom.i18n.resources"value = "Cn… .xxx.fileuploadMessage"/>
2. 여러 파일을 업로드하십시오
여러 파일 업로드, 배열 또는 목록을 사용할 수 있으며 다른 파일은 단일 파일 업로드와 유사합니다.
패키지 com.itheima.actions; import java.io.file; import java.io.ioexception; import org.apache.commons.io.fileutils; import org.apache.struts2.servletactionContext; import com.opensymphony.xworksupport; // 파일 업로드 : Private uppport {private uppport {private string orername; 개인 파일 [] 사진; // 양식의 업로드 필드 이름과 일치합니다. 유형은 파일 유형입니다. array 또는 list private string [] photofilename; // 파일 이름 개인 문자열 [] photocontentType; // 업로드 파일 mime public string upload () {// 업로드 필드 : 폴더에 업로드. 응용 프로그램의 이미지 디렉토리 문자열 realpath = servletactionContext.getServletContext (). getRealPath ( "/images")에 저장; 파일 디렉토리 = 새 파일 (realPath); if (! directory.exists ()) {drierce.mkdirs (); } try {for (int i = 0; i <photo.length; i ++) {fileUtils.copyFile (photo [i], 새 파일 (디렉토리, Photofilename [i])); } 반환 성공; } catch (ioexception e) {e.printstacktrace (); 반환 오류; }}}3. 파일 다운로드
원리 : struts2는 스트림 결과 유형을 제공하며, 이는 파일 다운로드 기능을 지원하는 데 특별히 사용되는 지정된 스트림 결과 유형입니다. 입력 이름 매개 변수를 지정해야합니다. 이 매개 변수는 입력 스트림을 지정하고 다운로드 된 파일에 대한 항목을 제공합니다.
코딩 단계 :
1) 액션 클래스 다운로드 :
패키지 com.ithema.actions; import java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.inputStream; import java.net.urlencoder; import org.apache.commons.io.filenameutils; import org.spercache.Struts com.opensymphony.xwork2.actionSupport; public class download actionsuctionsupport {private inputStream image; // 개인 문자열 파일 이름에 문제가있는 경우; // 파일 이름 private long filesize; public inputStream getImage () {return image; } public void setImage (inputStream image) {this.image = image; } public String getFileName () {return filename; } public long getfilesize () {return filesize; } public string download ()는 예외를 던집니다 {// image byte string에 값을 할당 string filerealpath = servletactionContext.getServletContext (). getRealPath ( "/web-inf/classe/如 .jpg"); filename = filenameutils.getName (filerealPath); // 메소드 1 : 중국 파일은 URL 인코딩되어야합니다. // filename = urlencoder.encode (filename, "utf-8"); filesize = 새 파일 (filerealPath) .length (); System.out.println (filename); image = new FileInputStream (FilerEalPath); 반환 성공; }}struts.xml 구성 파일 : 주로 스트림 유형의 결과를 구성합니다.
<struts> <constant name = "struts.devmode"value = "true" /> <constant name = "struts.ognl.ognl.alowstaticMethodaccess"value = "true" /> <action name = "download" "download"> <result type = "stream"> <stream "> <in inputname"> 이미지 < /param> <! inputStream-> <param name = "contenttype"> application/octet-stream </param> <!-브라우저 응답 헤더, 파일의 마임 형식을 알려주고 행동중인 getContentType 메소드를 호출하여 struts.xml에서 getContentType 메소드를 호출하여 액션 클래스에서 속성 값을 얻습니다. 액션 클래스에서 getFilename ()을 호출하십시오-> <!-중국 파일 이름 인코딩 : 메소드 2. Ognl 표현식을 사용하여 UrlenCode의 정적 메소드를 호출합니다-> <!-기본 OGNL 통화 정적 메소드를 수행 할 수 없습니다. 당신은 constant switch.struts.ognl.allowstaticmethodaccess = true-> <param name = "contentDisposition"> 첨부; 첨부; filename = $ {@java.net.urlencoder@encode (filename, 'utf-8')}}}}} </param> <!-브라우저를 다운로드하는 방법을 알려줍니다. </결과> </action> </package> </struts> 인터셉터와 파일 업로드는 여기에서 끝납니다. 너무 피곤하지만 성취로 가득합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.