Struts2 File Upload (2): manually filter uploaded files

Source: Internet
Author: User

Most of the time, web applications do not allow viewers to upload files freely, especially executable files, which may be virus programs. Generally, you can allow the viewer to upload images and compress files. In addition, you must set the file size uploaded by the viewer. Therefore, you must filter files during file upload. This article only discusses filtering file types.

From the action in the Form file field, we can see that there are two methods in it to obtain the file type and size respectively. To filter files, you can filter files by judging the return values of these two methods.

To manually filter files, follow these steps:

① Configure an allowedtypes parameter for action in struts. xml. The types are separated by commas.

<param name="allowedTypes">image/png,image/gif,image/jpeg</param>

② Add a string-type allowedtypes attribute in uploadaction. Java, and add the corresponding setter and getter methods.

private String allowedTypes;public String getAllowedTypes() {return allowedTypes;}public void setAllowedTypes(String allowedTypes) {this.allowedTypes = allowedTypes;}

③ Define a method specifically used for file filtering in uploadaction. Java and set the method name. The logic of this method is to determine whether the type of the uploaded file is allowed. If the type is allowed, null is returned. If the type is not allowed, a string is returned.

public String filterTypes(String[] types){String realType=getFileContentType();for(String type:types){if(type.equals(realType)){return null;}}return ERROR;}

④ Use struts2 input validation to determine whether the file type entered by the user meets the requirements. If not, add the error prompt to fielderror.

Public void validate () {string filterresult = filtertypes (getallowedtypes (). Split (","); If (filterresult! = NULL) {This. addfielderror ("file", "the file type you uploaded is not allowed ");}}

⑤ Because the input logic view is automatically returned when file type verification fails, you also need to add a physical view corresponding to the input logic view for action in struts. xml.

<result name="input">/fileupload.jsp</result>

The complete code is provided below:

Fileupload. jsp:

<% @ Page contenttype = "text/html; charset = UTF-8 "pageencoding =" UTF-8 "%> <% @ taglib prefix =" S "uri ="/Struts-tags "%> <HTML> 

Struts. xml:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"    "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts>    <package name="demo" extends="struts-default">        <action name="upload" class="action.UploadAction">            <param name="savePosition">/uploadDir</param>            <param name="allowedTypes">image/png,image/gif,image/jpeg</param>            <result name="success">/success.jsp</result>            <result name="input">/fileupload.jsp</result>        </action>    </package>    </struts>

Uploadaction. Java:

Public class uploadaction extends actionsupport {private file; private string filecontenttype; private string filefilename; private string saveposition; private string allowedtypes; Public file GetFile () {return file ;} public void setfile (File file) {system. out. println ("setfile () called"); this. file = file;} Public String getfilecontenttype () {return filecontenttype;} public void setfilecontenttype (string Filecontenttype) {system. out. println ("setfilecontenttype () called"); this. filecontenttype = filecontenttype;} Public String getfilefilename () {return filefilename;} public void setfilefilename (string filefilename) {system. out. println ("setfilefilename () called"); this. filefilename = filefilename;} Public String getsaveposition () {return saveposition;} public void setsaveposition (string saveposition) {system. out. Println ("setsaveposition () called"); this. saveposition = saveposition;} Public String getallowedtypes () {return allowedtypes;} public void setallowedtypes (string allowedtypes) {This. allowedtypes = allowedtypes;} @ overridepublic string execute () throws exception {system. out. println (getfilecontenttype (); string realpath = servletactioncontext. getservletcontext (). getrealpath (getsaveposition (); fileoutputstream Fos = new fileoutputstream (realpath + file. separator + getfilefilename (); fileinputstream FD = new fileinputstream (GetFile (); byte [] buffer = new byte [1024]; int Len = 0; while (LEN = FCM. read (buffer ))! =-1) {FOS. write (buffer, 0, Len);} return "success";} Public String filtertypes (string [] types) {string realtype = getfilecontenttype (); For (string type: types) {If (type. equals (realtype) {return NULL ;}} return error;} public void validate () {string filterresult = filtertypes (getallowedtypes (). split (","); If (filterresult! = NULL) {This. addfielderror ("file", "the file type you uploaded is not allowed ");}}}

Success. jsp:

<% @ Page contenttype = "text/html; charset = UTF-8 "pageencoding =" UTF-8 "%> <% @ taglib prefix =" S "uri ="/Struts-tags "%> <HTML> 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.