1. struts2 파일 업로드
struts2의 파일 업로드 구현은 매우 간단하며 몇 가지 간단한 단계만으로 완료 할 수 있습니다.
알아채다:
(1) 파일 업로드의 struts2 태그는 다음과 같습니다. <s : file name = ""label = "ubload"/>
(2) 파일 업로드의 전제 조건은 Form Attribution Method = "Post"EncType = "multipart/form-data"입니다.
(3) Web Application에는 Common-FileUpload.jar 및 Common-Io.jar가 포함되어야합니다. Struts2의 기본 업로드 파서가 Jakarta를 사용하기 때문입니다.
(4) 허용 된 최대 파일 크기는 struts.xml로 구성 될 수 있습니다. <constant name = "struts.multipart.maxsize"value = "......"/>, 기본값은 2m입니다.
1. 일반 파일 업로드 <br /> 구현 규칙 :
(1) jsp <s : file name = "Upload"label = "Upload"에서 양식 컨트롤을 설정합니다.
(2) 실제로 속성을 정의하십시오.
개인 파일 업로드; // 파일 내용을 포함합니다
개인 문자열 uploadFilename; // 업로드 된 파일의 이름;
비공개 문자열 업로드 컨텐츠 타입; // 업로드 파일의 마임 유형;
이 속성은 파일이 업로드 될 때 자동으로 할당됩니다.
(3) execute ()에서 디스크 쓰기 함수를 완료합니다.
Code example:
UPLOAD01Action.java
패키지 org.upload.action; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import org.apache.struts2.servletactionContext; com.opensymphony.xwork2.actionSupport 가져 오기; 공개 클래스 업로드 01Action은 ActionSupport {private file upload; 개인 문자열 uploadFilename; 비공개 문자열 업로드 컨텐츠 타입; 개인 문자열 이름; public string execute ()는 예외 {string path = servletactionContext.getServletContext (). getRealPath ( "/web-inf/upload"); 문자열 filename = path+file.separator+이름; fileInputStream in = new FileInputStream (업로드); fileoutputStream out = 새 FileOutputStream (filename); 바이트 [] B = 새로운 바이트 [1024]; int len = 0; while ((len = in.read (b))> 0) {out.write (b, 0, len); } out.close (); 반환 성공; } 공개 파일 getUpload () {return ubload; } public void setUpload (파일 업로드) {this.upload = 업로드; } public String getUploadFilename () {return uploadFilename; } public void setUploadFileName (String uploadFilename) {this.uploadFilename = uploadFilename; } public String getUploadContentType () {return uploadContentType; } public void setUploadContentType (String uploadContentType) {this.uploadContentType = uploadContentType; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; }} struts.xml
<? xml version = "1.0"encoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <constant name = "struts.custom.i18n.resources"value = "message"> </constant> <패키지 이름 = "default"namespace = "/"extends = "struts-default"> <action name = "upload0*"> <param name = "name"> 1.jpg </param> <result> {1}. 1.JSP
<%@ page language = "java"import = "java.util.*"pageEncoding = "utf-8"%> <%@ taglib prefix = "s"uri = "/struts-tags"%> <! doctype html publ "-// w3c // dtd html 4.01 transitional // <html> <html> <html> <html> '1.jsp'시작 페이지 </title> </head> <body> <s : form action = "upload01"method = "post"encticpe = "multipart/form-data"> <s : file name = "upload"label = "upload"> </s : 파일> <s : 제출 값 = "upload"> </s : 제출> </html> </html> </html> </html>
2. 인터셉터를 사용하여 필터를 사용하십시오
필터링을 수동으로 구현하는 방법은 매우 간단합니다. 이는 입력 검증을 필터에 사용하는 것, 즉 validate ()에서 필터링하는 것입니다.
우리가 여기서 이야기하고 싶은 인터셉터 방법은 좋은 방법입니다. 구성 파일에서만 구성하면됩니다. 유연성이 우수하며 파일 유형과 파일 크기를 제한 할 수 있습니다. 업로드 된 파일이 요구 사항을 충족하지 않으면 입력 논리보기를 반환합니다.
인터셉터 구성 단계 :
(1) 파일 업로드의 인터셉터는 FileUpload입니다.
(2) 주어진 매개 변수는 허용 유형 및 최대 크기 여야합니다.
(3) FileUpload 인터셉터 후 <Interceptor-Ref Name = "DefaultStack"/>를 추가해야합니다.
Code example:
인터셉터를 통한 필터링에는 struts.xml 구성 만 있으면 struts.xml의 구성 만 여기에 제공됩니다.
<? xml version = "1.0"encoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <constant name = "struts.custom.i18n.resources"value = "message"> </constant> <package namespace = "default"namespace = "/"extends = "struts-default"> <action name = "upload0*"> <interceptor-ref name = "fileUpload"> <arevertypes "> image/gime/gimate/gime/gifeg, 이미지/gifeg, 이름 = "maximsize"> 1024*1024 </param> </interceptor-ref> <interceptor-ref name = "defaultStack"> </interceptor-ref> <param name = "name"> 1.jpg </param> <result>/{1} .jsp </action> </package> </struts> 또한 구성 파일 업로드가 실패한 후 오류 메시지가 필요하며 글로벌 국제 리소스 파일에서 구성해야합니다.
struts.messages.error.content.type.not.allowed = 파일 유형은 struts.messages.error.file.too.large = 파일이 너무 큽니다
2. struts2 파일을 다운로드하십시오
서블릿과 HTTP 프로토콜을 배울 때 이미 파일 다운로드, 즉 컨텐츠 방향 헤더를 작성할 수 있습니다. 이것은 Struts2의 구현 원리이지만 더 나은 캡슐화를 제공합니다.
Struts2의 스트림 결과 유형은 특히 파일 다운로드를 구현하는 데 사용됩니다.
(1) struts.xml에서 스트림 결과 유형을 구성하고 ContentType, ContentDisposition 및 Buffersize 매개 변수를 구성하십시오. 주형:
<action name = "download"> <result type = "stream"이름 = "success"> <param name = "contentType"> </param> <param name = "contentDisPosition"> 첨부; filename = ""</param> <param name = "buffersize"> 4096 </param> </result> </action>
(2) 공개 입력 스트림 getInputStream ()을 생성하여 예외는 행동에 예외를 던집니다. 방법,이 방법은 다운로드 된 파일의 입력 스트림을 얻는 데 사용됩니다.
downloadAction.java
패키지 org.download.action; import java.io.inputstream; import org.apache.struts2.servletactionContext; com.opensymphony.xwork2.actionSupport 가져 오기; 공개 클래스 다운로드 확장 actionSupport {public inputStream getInputStream ()은 예외 {return servletactionContext.getServletContext (). getResourCeasStream ( "/web-inf/upload/1.jpg"); } public string execute ()는 예외 {return success; }} struts.xml
<action name = "download"> <result type = "stream"이름 = "success"> <param name = "contenttype"> image/jpeg </param> <param name = "contentDisposition"> 첨부; filename = "1.jpg"</param> <param name = "buffersize"> 4096 </param> </action>
다운로드를 완료 할 수 있습니다.
이는 Java에서 Struts2 파일을 업로드하고 다운로드하는 구현을 소개하는 것입니다. 읽어 주셔서 감사합니다.