1. Upload Struts2 file
The file upload implementation of Struts2 is very simple and can be completed in just a few simple steps;
Notice:
(1) The struts2 tag for file upload is: <s:file name="" label="upload"/>
(2) The prerequisite for file upload is the form attribute method="post" enctype="multipart/form-data";
(3) The web application must include common-fileupload.jar and common-io.jar, because the default upload parser of struts2 uses jakarta;
(4) The maximum allowed file size can be configured in struts.xml: <constant name="struts.multipart.maxSize" value="......"/>, default is 2M;
1. Normal file upload <br />Implementation rules:
(1) Set the form control in JSP <s:file name="upload" label="upload"/>
(2) Define attributes in Action:
private File upload; //Includes file content
private String uploadFileName; //The name of the uploaded file;
private String uploadContentType; //The MIME type of upload file;
These attributes will be automatically assigned as the file is uploaded;
(3) Complete the disk write function in execute();
Code example:
Upload01Action.java
package org.upload.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class Upload01Action extends ActionSupport { private File upload; private String uploadFileName; private String uploadContentType; private String name; public String execute()throws Exception{ String path = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload"); String filename = path+File.separator+name; FileInputStream in = new FileInputStream(upload); FileOutputStream out = new FileOutputStream(filename); byte[]b = new byte[1024]; int len = 0; while((len=in.read(b))>0){ out.write(b,0,len); } out.close(); return SUCCESS; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = 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(String name) { this.name = name; } } struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="message"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="upload0*"> <param name="name">1.jpg</param> <result>/{1}.jsp</result> </action> </package> </struts> 1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP '1.jsp' starting page</title> </head> <body> <s:form action="upload01" method="post" enctype="multipart/form-data"> <s:file name="upload" label="upload"></s:file> <s:submit value="upload"></s:submit> </s:form> </body> </html>
2. Use interceptors to filter
The method of manually implementing filtering is very simple, which is to use input verification to filter, that is, filtering in validate();
The interceptor method we want to talk about here is a good way. It only needs to be configured in the configuration file. It has good flexibility and can limit the file type and file size. If the uploaded file does not meet the requirements, it will return the input logical view;
Steps to configure the interceptor:
(1) The interceptor for file upload is fileUpload;
(2) The given parameters are required to be allowedTypes and maximumSize;
(3) After the fileUpload interceptor, you need to add <interceptor-ref name="defaultStack"/>
Code example:
Since filtering through an interceptor only requires configuring struts.xml, only the configuration of struts.xml is given here.
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="message"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="upload0*"> <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/jpeg,image/gif</param> <param name="maximumSize">1024*1024</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> <param name="name">1.jpg</param> <result>/{1}.jsp</result> </action> </package> </struts> We also need the error message after the configuration file upload fails, and we need to configure it in the global international resource file:
struts.messages.error.content.type.not.allowed=File type does not match struts.messages.error.file.too.large=File is too large
2. Download Struts2 file
When we learn Servlet and HTTP protocols, we can already implement file downloads, that is, write content-disposition header. This is the implementation principle of struts2, but it provides better encapsulation;
The stream result type of struts2 is specifically used to implement file downloads;
(1) Configure the stream result type in struts.xml, and configure contentType, contentDisposition, and bufferSize parameters. Template:
<action name="download"> <result type="stream" name="success"> <param name="contentType"></param> <param name="contentDisposition">attachment;filename=""</param> <param name="bufferSize">4096</param> </result> </action>
(2) Create public InputStream getInputStream()throws Exception in Action; method, this method is used to obtain the input stream of the downloaded file;
DownloadAction.java
package org.download.action; import java.io.InputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class DownloadAction extends ActionSupport { public InputStream getInputStream()throws Exception{ return ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/upload/1.jpg"); } public String execute()throws Exception{ return SUCCESS; } } struts.xml
<action name="download"> <result type="stream" name="success"> <param name="contentType">image/jpeg</param> <param name="contentDisposition">attachment;filename="1.jpg"</param> <param name="bufferSize">4096</param> </result> </action>
You can complete the download.
This is all for you to introduce the implementation of uploading and downloading struts2 files in Java. Thank you for your reading.