The Servlet 3.0 specification HttpServletRequest has provided a method to handle file uploads, but such uploads need to be done in the Servlet. Struts2 provides a simpler package.
Struts2 uses Jakarta's Common-FileUpload file upload framework by default. Therefore, using Struts2's file upload function, you need to add two jar packages, namely commons-io-2.2.jar and commons-fileupload-1.3.1.jar.
Struts2 simple file upload example:
1. File upload page
In order to upload files, the method of the form must be set to POST and the enctype is set to multipart/form-data. Once the enctype is set to multipart/form-data, the browser will use binary streams to process form data.
<%@ taglib prefix="s" uri="/struts-tags" %><%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/1/16 Time: 14:06 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Struts2 Simple file upload</title></head><body> <s:form action="file_upload" method="POST" enctype="multipart/form-data"> <s:file name="upload" label="select file"/> <s:submit value="upload"/> </s:form></body></html>
2. Process the upload request action
/** * Description:Struts2 simple file upload* Author: Eleven * Date: 2018/1/24 10:39 */public class FileAction extends ActionSupport{ //Upload file private File upload; //Upload file type private String uploadContentType; //Upload file name private String uploadFileName; //Upload file upload allowedTypes; private String allowTypes are dynamically set in struts.xml using the param tag; public String page(){ return "page"; } public void upload() { //Upload: //1. Read the file content//2. Write the file content to the specified file try{ System.out.println("File upload allowed type="+allowTypes); String realPath = ServletActionContext.getServletContext().getRealPath("/upload"); System.out.println("Absolute path of the project="+realPath); //Create the file save directory new File(realPath).mkdir(); File file = new File(realPath+"/"+uploadFileName); //Create if(!file.exists()){ file.createNewFile(); } FileOutputStream out = new FileOutputStream(file); FileInputStream in = new FileInputStream(upload); byte[] buffer = new byte[1024]; int len = 0; //Write while reading and writing 1kb each time Write 1kb while((len = in.read(buffer))>0){ out.write(buffer,0,len); } System.out.println("File upload successfully..."); } catch(Exception e){ e.printStackTrace(); } } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = 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 getAllowTypes() { return allowTypes; } public void setAllowTypes(String allowTypes) { this.allowTypes = allowTypes; }}If the form contains a file field with name attribute xxx, then the corresponding Action needs to use three member variables to encapsulate the information of the file field.
The xxx member variable of type File encapsulates the file content corresponding to the file field.
The xxxFileName member variable of type String encapsulates the file name of the file corresponding to the file field.
The xxxContentType member variable of type String encapsulates the file type of the file corresponding to the file field.
3. Configure struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!--File Upload--> <action name="file_*" method="{1}"> <result name="page">/WEB-INF/jsp/fileUpload.jsp</result> <!--Dynamic setting of action properties. Here is an example to set the type that allows file uploads, but the action program does not do much processing --> <param name="allowTypes">image/png,image/gif,image/jpeg</param> </action> </package></struts>Interceptor implements file filtering
Struts2 provides an interceptor for file upload, fileUpload. In order for this interceptor to work, the interceptor reference must be configured in the action.
When configuring a fileUpload interceptor, you can specify two parameters for it:
allowTypes: The file type allowed to be uploaded, separated by multiple file types with English commas
maximumSize: The file size allowed to be uploaded, in bytes.
When file filtering fails, the system automatically transfers to the input logical view, so the logical view named input must be configured for this Action. In addition, the interceptor reference of defaultStack must be configured for this Action as displayed.
The struts.xml configuration file is as follows:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!--File Upload--> <action name="file_*" method="{1}"> <!--Configure fileUpload interceptor and configure before defaultStack interceptor stack--> <interceptor-ref name="fileUpload"> <!--Allowed file type--> <param name="allowedTypes">image/png,image/gif,image/jpeg</param> <!--Allowed file size--> <param name="maximumSize">2000</param> </interceptor-ref> <!--Configure system default interceptor--> <interceptor-ref name="defaultStack"/> <!--Configure input view page--> <result name="input">/WEB-INF/jsp/input.jsp</result> <result name="page">/WEB-INF/jsp/fileUpload.jsp</result> </action> </package></struts>The file upload interceptor configured above requires that the file upload type can only be an image file, and the file size cannot be greater than 2000 bytes. If the uploaded file is too large or the type does not match, it will jump to the input logical view.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.