이 기사는 참조를 위해 struts2 파일의 업로드 및 다운로드를위한 특정 구현 코드를 공유합니다. 특정 내용은 다음과 같습니다
1. 파일 업로드
Struts가 제출 한 파일 구성 요소를 업로드하고
프론트 데스크 :
1) 제출 방법 게시물
2) 양식 유형 멀티 파트/폼 데이터
3) 입력 유형 = 파일
무대 뒤에서:
Apache에서 제공하는 FileUpload 구성 요소
핵심 범주 :
FileItemFactory FileItem Factory
ServletFileUpload 서플렛에서 파일 업로드 용 Core 클래스
FileItem은 업로드 된 양식 파일 항목의 정보를 캡슐화합니다. 요컨대, 파일 업로드는 처리하기에 더 번거 롭습니다.
Struts의 파일 업로드 <br /> 파일 업로드 인터셉터는 늦은 파일 업로드 기능에 도움이됩니다.
<인터셉터 이름 = "FileUpload"/>
upload.xml
<struts> <package name = "upload_"actends = "struts-default"> <!-참고 : 키워드 "fileUpload"는 키워드 "fileUpload"-> <action name = "fileUploadAction"> <!-업로드 된 파일 유형을 제한합니다-> <interceptor-ref name = "defaultStack"> <! 이름 = "fileUpload.allowEdextensions"> txt, jpg, jar </param> <!-[위와 동시에 실행되는 파일 유형 [param name = "fileUpload.allowedTypes"> text/plain>-> </interceptor-ref> <result name = "success"-jsp <! 이름 = "입력">/e/error.jsp </resent> </action> </package> </struts>
upload.jsp
<body> <form action = "$ {pagecontext.request.contextPath}/fileUploadAction"method = "post"encType = "multipart/form-data"> username : <input type = "instername">> 파일 : <input type = "file"name = "form <bb/> input type ="input type = "input type ="username "> <br/> </body>error.jsp
<body> error.jsp <br/> <!-런타임 동안 Struts 프레임 워크에서 생성 된 모든 오류 메시지보기-> < %@ taglib uri = "/struts-tags"prefix = "s" %> <s : fielderror> </s : fielderror> </body> success.jsp <body> success.jsp <jsp>
핵심 코드
fileUpload .class
public class fileUpload는 actionSupport {// 해당 양식을 확장합니다. <input type = "file"name = "file1"> 개인 파일 파일 1; // 파일 이름 개인 문자열 파일 1FILENAME; // 파일 유형 (MIME) 개인 문자열 파일 1ContentType; public void setfile1 (file file1) {this.file1 = file1; } public void setfile1filename (String file1filename) {this.file1filename = file1filename; } public void setFile1contentType (String file1contentType) {this.file1contentType = file1contentType; } @override public string () excepte ()는 예외를 던집니다. {/********** 업로드 된 파일을 가져와 처리하고 처리 *******/// 파일을 업로드 디렉토리에 업로드 // 업로드 된 디렉토리 경로를 가져옵니다. // 대상 파일 생성 파일 파일 DestFile = 새 파일 (path, file1filename); // 업로드 된 파일을 대상 FILEUTILS.COPYFILE (file1, destFile)에 복사합니다. 반환 성공; }} 파일 업로드 처리 세부 정보
에이. 파일 크기 제한
Structs에서 지원하는 최대 파일 업로드는 기본적으로 2m이며 상수로 수정됩니다.
<!-4. 업로드 된 파일의 최대 크기를 30m로 수정하십시오->
<constant name = "struts.multipart.maxsize"value = "31457280"/>
비. 허용 가능한 유형의 업로드 된 파일 제한 : txt/jpg 접미사를 가진 파일 인터셉터 만 허용됩니다. 파일 업로드 유형을 제한하기 위해 매개 변수를 주입합니다.
<!-업로드 된 파일 유형을 제한-> <interceptor-ref name = "defaultstack"> <!-파일의 확장 제한-> <param name = "fileUpload.allowedextensions"> txt, jpg, jar </param> <!-[위와 같은 시간에 사용 된 파일 유형을 제한] 이름 = "FileUpload.allowedTypes"> Text/Plain </param>-> </interceptor-Ref>
2. 파일을 다운로드하십시오
Struts 파일 다운로드, 두 가지 방법 :
방법 1 : 응답 객체를 통해 바이트 스트림 데이터를 브라우저에 쓰기; 다운로드 2에 대한 응답 헤더 메소드 설정 : Struts Method
Struts 파일 다운로드 :
다음과 같이 코드를 복사하십시오. <result-type name = "stream"/>
먼저 Webroot 디렉토리에 새 업로드 폴더를 생성하고 제공하려는 파일을 다운로드 한 폴더에 넣습니다.
upload.xml
<action name = "down_*"method = "{1}"> <!-목록 디스플레이-> <result name = "list">/e/list.jsp> <!-다운로드 작업-> <result name = "download"type = "stream"> <!-모든 이진 파일 유형으로 실행되는 파일 유형 :> <param name = "contenttype"> application <! 스트림의 속성을 반환 [실제로 getAttrinputStream ()]-> <param name = "inputname"> attrinputStream </param> <!-다운로드 헤더 (브라우저에서 표시되는 파일 이름)-> <param name = "contentDisPosition"> 첨부; 첨부; downFilename} </param seting-> <param bubler seting. name = "buffersize"> 1024 </param> </result> </action>list.jsp
<bod> align = "center"> <tr> <td> 번호 </td> <td> 파일 이름 </td> <td> 작동 </td> </td> < %@tglib uri = "http://java.sun.com/jsp/jstl/core"prefix = "c" %> <c : foreach = "foreach =". 항목 = "$ {filenames}"varstatus = "vs"> <tr> <td> $ {vs.count} </td> <td> {filename} </td> <td> <!-URL 빌드-> <c : url var = "url"value = "down_down"> <c : param name = "filename =" "" value = "$ {filename}"> </c : param> </c : url> <a href = "$ {url}"> 다운로드 </a> </td> </tr> </c : foreach> </table> </body>다운 action
/***파일 다운로드*1. 다운로드 할 모든 파일 목록을 표시*2. 파일 다운로드** /public class 다운로드 ActionSupport 확장 { /********************* 1. Show the list of all files to be downloaded****************************/ public String list() throws Exception { //Get the upload directory path String path = ServletActionContext.getServletContext().getRealPath("/upload"); // 디렉토리 개체 파일 = 새 파일 (Path); // 다운로드 할 모든 파일의 파일 이름을 가져옵니다. String [] filenames = file.list (); // ActionContext AC = ActionContext.getContext () 저장; // 요청을 나타내는 맵을 가져옵니다. request.put ( "filenames", filenames); "목록"을 반환합니다. } /****************** 2. 파일 다운로드 ******************************* // 1. 파일의 파일 이름을 다운로드 할 개인 문자열 filename; public void setfilename (String filename) {// 전달 된 매개 변수의 문제를 처리합니다 (제출) try {filename = new String (filename.getBytes ( "ISO8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) {throw new runtimeexception (e); } // this.filename = filename; } // 2. 제출 된 비즈니스 방법을 다운로드하십시오 (struts.xml에서 스트림 구성) public string () down ()은 예외 {return "download"; } // 3. 파일 스트림을 반환하는 메소드 public inputStream getAttrinputStream () {return servletactionContext.getServletContext (). getResourCeasStream ( "/upload/" + filename); } // 4. 표시된 파일 이름을 다운로드 (브라우저에서 표시된 파일 이름) 공개 문자열 getDownFilename () {// 중국 인코딩이 필요합니다. {filename = urlencoder.encode (filename, "utf-8"); } catch (UnsupportedEncodingException e) {throw new runtimeexception (e); } 리턴 파일 이름; }}위의 내용은이 기사에 관한 모든 것입니다. 모든 사람의 학습에 도움이되기를 바랍니다.