Pages

Thursday, April 4, 2013

[Struts 2] upload file

Ứng dụng upload file lên server với Struts 2.

Trong ví dụ dưới đấy sẽ refer tới  FileUploadInterceptor để thực hiện ứng dụng upload file.
Lưu ý rằng  FileUploadInterceptor được based trên MultiPartRequestWrapper,do vậy mọi request có refer tới file upload interceptor sẽ được tư động áp dụng tới các file element trên HTML Form.

JSP page.
Action Class ( extends ActionSupport Class ).
Trong action class ta cần tương ứng 3 biến như trên, ý nghĩa mỗi trường : 
ý nghĩa :
  • [File Name] : File - the actual File
  • [File Name]ContentType : String - the content type of the file
  • [File Name]FileName : String - the actual name of the file uploaded (not the HTML name)
cú pháp 3 setter phải theo convention sau : trong đó X = thuộc tính name của file upload Element trên HTML Form.
Method SignatureDescription
setX(File file)The file that contains the content of the uploaded file. This is a temporary file and file.getName() will not return the original name of the file
setXContentType(String contentType)The mime type of the uploaded file
setXFileName(String fileName)The actual file name of the uploaded file (not the HTML name)

Struts action mapping
Note : fileUpload interceptor cho phép ta pass một số param liên quan tới file upload như : content type của file cho phép, kích thước file upload....

Mores :
http://struts.apache.org/release/2.0.x/struts2-core/apidocs/org/apache/struts2/interceptor/FileUploadInterceptor.html

http://struts.apache.org/release/2.0.x/docs/file-upload.html
http://struts.apache.org/release/2.0.x/struts2-core/apidocs/org/apache/struts2/dispatcher/multipart/MultiPartRequestWrapper.html

No comments:

Post a Comment