Servlet 3.0 사양 httpservletrequest는 파일 업로드를 처리하는 방법을 제공했지만 이러한 업로드는 서블릿에서 수행해야합니다. struts2는 더 간단한 패키지를 제공합니다.
Struts2는 기본적으로 자카르타의 공통 파일로드 파일 업로드 프레임 워크를 사용합니다. 따라서 Struts2의 파일 업로드 기능을 사용하면 Commons-IO-2.2.jar 및 Commons-FileUpload-1.3.1.jar의 두 개의 JAR 패키지를 추가해야합니다.
struts2 간단한 파일 업로드 예 :
1. 파일 업로드 페이지
파일을 업로드하려면 양식의 메소드를 게시하도록 설정하고 ENCTYPE는 멀티 파트/양식 데이터로 설정되어야합니다. ENCTYPE가 Multipart/Form-Data로 설정되면 브라우저는 이진 스트림을 사용하여 양식 데이터를 처리합니다.
<%@ taglib prefix = "s"uri = "/struts-tags"%> <%-Intellij Idea에 의해 생성됩니다. 사용자 : 관리자 날짜 : 2018/1/16 시간 : 14:06이 템플릿을 변경하려면 파일 | 설정 | 파일 템플릿 .--%> <%@ page contenttype = "text/html; charset = utf-8"language = "java"%> <html> <head> <title> struts2 간단한 파일 업로드 </title> </head> <body> <s : form action = "file_upload"method = "post"interlogate "> form-data"> form-data ": label = "파일 선택"/> <s : 제출 값 = "업로드"/> </s : form> </body> </html>
2. 업로드 요청 조치를 처리하십시오
/** * 설명 : struts2 간단한 파일 업로드 * 저자 : 11 개의 * 날짜 : 2018/1/24 10:39 */public class fileAction 확장 actionSupport {// 파일 비공개 파일 업로드; // 파일 유형을 업로드 개인 문자열 업로드 ContentType; // 파일 이름을 업로드 개인 문자열 업로드 필레나 이름; // 파일 업로드 허용 유형; Param Tag를 사용하여 struts.xml에서 개인 문자열 allowTypes가 동적으로 설정됩니다. 공개 문자열 page () {return "page"; } public void upload () {// ubload : // 1. 파일 내용을 읽으십시오 // 2. 지정된 파일에 파일 내용을 쓰기 {system.out.println ( "파일 업로드 허용 유형 ="+allowtypes); String realPath = servletActionContext.getServletContext (). getRealPath ( "/upload"); System.out.println ( "Project의 절대 경로 ="+realPath); // 파일 생성 디렉토리 저장 새 파일 (realPath) .mkdir (); 파일 = 새 파일 (realPath+"/"+uploadFilename); // if (! file.exists ()) {file.createnewfile (); } fileoutputStream out = 새 FileOutputStream (파일); fileInputStream in = new FileInputStream (업로드); 바이트 [] 버퍼 = 새로운 바이트 [1024]; int len = 0; // 1kb를 읽고 쓸 때마다 1kb를 쓸 때 씁니다. } system.out.println ( "파일 업로드가 성공적으로 ..."); } catch (예외 e) {e.printstacktrace (); }} 공개 파일 getUpload () {return ubload; } public void setUpload (파일 업로드) {this.upload = 업로드; } public String getUploadContentType () {return uploadContentType; } public void setUploadContentType (String uploadContentType) {this.uploadContentType = uploadContentType; } public String getUploadFilename () {return uploadFilename; } public void setUploadFileName (String uploadFilename) {this.uploadFilename = uploadFilename; } public String getalowTypes () {return allowTypes; } public void setallowTypes (String allowTypes) {this.allowTypes = allowTypes; }}양식에 이름 속성 xxx가있는 파일 필드가 포함 된 경우 해당 조치는 파일 필드의 정보를 캡슐화하기 위해 세 가지 멤버 변수를 사용해야합니다.
파일 유형의 xxx 멤버 변수는 파일 필드에 해당하는 파일 컨텐츠를 캡슐화합니다.
xxxfilename type string의 xxxfilename 멤버 변수는 파일 필드에 해당하는 파일의 파일 이름을 캡슐화합니다.
xxxcontenttype 유형 문자열의 멤버 변수는 파일 필드에 해당하는 파일의 파일 유형을 캡슐화합니다.
3. struts.xml을 구성하십시오
<? xml version = "1.0"alcoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.3 // en" "http://struts.apache.org/dtds/struts-2.3.dtd "> struts> <constant name ="strut.endymmeThodation " value = "false"/> <constant name = "struts.devmode"value = "true"/> <packue name = "default"namespace = "/"extends = "struts-default"> <!-파일 업로드-> <action name = "file_*"method = "{1}"> result name = "page"/web-inf/jsp/appload의 actup/appload of acture of at actup/jsp/appload. 속성. 다음은 파일 업로드를 허용하는 유형을 설정하는 예입니다. 그러나 액션 프로그램은 많은 처리를 수행하지 않습니다 -> <param name = "allowtypes"> image/png, image/gif, image/jpeg </param> </action> </package> </struts>인터셉터는 파일 필터링을 구현합니다
struts2는 파일 업로드, fileUpload에 대한 인터셉터를 제공합니다. 이 인터셉터가 작동하려면 인터셉터 참조를 동작에서 구성해야합니다.
FileUpload 인터셉터를 구성 할 때는 두 가지 매개 변수를 지정할 수 있습니다.
allowtypes : 영어 쉼표로 여러 파일 유형으로 분리 할 수있는 파일 유형을 업로드 할 수 있습니다.
최대 규모 : 파일 크기를 바이트로 업로드 할 수 있습니다.
파일 필터링이 실패하면 시스템이 입력 논리보기로 자동 전송되므로 입력이라는 논리보기 가이 작업에 대해 구성되어야합니다. 또한 기본 스택의 인터셉터 참조는 표시된 대로이 작업에 대해 구성해야합니다.
struts.xml 구성 파일은 다음과 같습니다.
<? xml version = "1.0"alcoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.3 // en" "http://struts.apache.org/dtds/struts-2.3.dtd "> struts> <constant name ="strut.endymmeThodation " value = "false" /> <constant name = "struts.devmode"value = "true" /> <packue name = "default"namespace = " /"extends = "struts-default"> <!-파일 업로드-> <action name = "file_*"method = "{1}"> <!-defaultop-inter stack intercrector-stack intercrecter-ter intercrector intercrecter-intercrect intercrect intercrect intercrect intercrect intercrect intercrect intercrect intercrep-terfect intercrect-interpigure interpigu 이름 = "fileUpload"> <!-허용 파일 유형-> <param name = "alluctTypes"> image/png, image/gif, image/jpeg </param> <!-허용 파일 크기-> <param name = "maxumSize"> 2000 </param> </param> </param> <interceptor-ref> <!-intercepor-ref off "" "> <!-입력보기 페이지-> <결과 이름 = "input">/web-inf/jsp/input.jsp </result> <result name = "page">/web-inf/jsp/fileUpload.jsp </action> </struts> </struts>위에서 구성된 파일 업로드 인터셉터는 파일 업로드 유형이 이미지 파일 만 가능하고 파일 크기는 2000 바이트보다 클 수 없습니다. 업로드 된 파일이 너무 크거나 유형이 일치하지 않으면 입력 논리보기로 이동합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.