Let’s first talk about the principles of uploading and downloading instance implementation of struts2:
Struts 2 is uploaded through Commons FileUpload file.
Commons FileUpload uses the fileUpload interceptor to bind the file to an instance of Action by saving HTTP's data to a temporary folder, and then Struts uses the fileUpload interceptor. Thus, we can operate the files uploaded by the browser in a local file manner.
Specific implementation :
1. Create index.jsp page
<body> <s:form action="upload" method="post" theme="simple" enctype="multipart/form-data"><table align="center"><tr> <td>Select upload file</td> <td id="more"> <s:file name="file"></s:file> <input type="button" value="Add More.." onclick="addMore()"> </td> </tr><tr> <td><s:submit type="button" value="submit" onclick="return checkf()"/></td> <td><s:reset value="reset "></s:reset></td> </tr></table><table align="center"><tr><td>test.txt</td><td> <a href="<s:url value='download.action'><s:param name='fileName'>test.txt</s:param> </s:url>">Download</a></td></tr></table></s:form></body>
Create result.jsp page
<body><s:form> <div style="border:1px solid black">File uploaded successfully:<br> <ul style="list-style-type:decimal"> <s:iterator value="#request.fileName" id="file" status="status"> <li><s:property/> </li> </s:iterator> </ul> </div></s:form></body>
Of course, don't forget to add struts2 tag reference on each page <%@taglib prefix="s" uri="/struts-tags" %>
2. Create an updown.js file and reference it in index.jsp
function checkf(){ var files = document.getElementsByName("file"); if(files[0].value.length!=0){ return true; }else{ alert("Please select file"); return false; }}function addMore(){ var td = document.getElementById("more"); var br = document.createElement("br"); var input = document.createElement("input"); var button = document.createElement("input"); input.type = "file"; input.name = "file"; button.type = "button"; button.value = "Remove"; button.onclick = function() { td.removeChild(br); td.removeChild(input); td.removeChild(button); } td.appendChild(br); td.appendChild(input); td.appendChild(button); } 3. Create upDownloadAction.java
package com.action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.util.List;import javax.servlet.http.HttpServletRequest;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.ServletActionContext;public class UpDownloadAction extends ActionSupport { private static final long serialVersionUID = 1L; private List<File> file;// Corresponding to file tags in jsp private List<String> fileFileName;// private List<String> fileContentType;// private String fileName;// Obtain the pram parameter in jsp @SuppressWarnings("deprecation") // File upload public String uploadFiile() throws Exception { String root = ServletActionContext.getServletContext().getRealPath( "/upload");// Upload path System.out.println(root); InputStream inputStream; File destFile; OutputStream os; for (int i = 0; i < file.size(); i++) { inputStream = new FileInputStream(file.get(i)); destFile = new File(root, this.getFileFileName().get(i)); os = new FileOutputStream(destFile); byte[] buffer = new byte[400]; int length = 0; while ((length = inputStream.read(buffer)) > 0) { os.write(buffer, 0, length); } inputStream.close(); os.close(); } HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("fileName", fileFileName); return SUCCESS; } // File download public InputStream getDownloadFile() throws FileNotFoundException, UnsupportedEncodingException { System.out.println(getFileName()); // If the download file name is Chinese, perform character encoding conversion ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8")); InputStream inputStream = new FileInputStream("F:/" //Use the absolute path to download the "test.txt" file from this path + this.getFileName()); System.out.println(inputStream); return inputStream; } // Download public String downloadFile() throws Exception { return SUCCESS; } public String getFileName() throws UnsupportedEncodingException { return fileName; } public void setFileName(String fileName) throws UnsupportedEncodingException { this.fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8"); } }Note: The get and set methods of the attribute have been omitted.
Fourth, finally the configuration file
1. web.xml configuration
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2. Struts.xml configuration
<struts> <constant name="struts.i18n.encoding" value="utf-8"></constant> <constant name="struts.multipart.saveDir" value="f:/"></constant> <package name="struts2" extends="struts-default"> <action name="upload" method="uploadFiile"> <result name="success">/jsp/result.jsp</result> <interceptor-ref name="fileUpload"><!--maximumSize (optional) - The maximum length of the file uploaded to the action allowed by this interceptor (in byte units). Note that this parameter has nothing to do with the properties defined in webwork.properties. The default is 2MB--> <param name="maximumSize">409600</param><!--allowedTypes (optional) - A comma-separated list of contentType types (such as text/html). These lists are contentTypes allowed by this interceptor to pass to the action. If not specified, any upload type is allowed.--> <param name="allowedTypes"> text/plain </param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </action> <action name="download" method="downloadFile" > <result name="success" type="stream"> <!--Specify file download type application/octet-stream default value can download all types --> <param name="contentType"> application/txt; </param> <!--Specify the downloaded file name and display method, but pay attention to the garbled code of Chinese names. The solution is: encoding processing--> <!--contentDisposition is the processing method of file download, including inline and attachment. The default is inline. When using attachments, it is configured as follows: attachment;filename="filename" . --> <param name="contentDisposition"> attachment;filename="${fileName}" </param> <!--Get inputStream from getDownloadFile() method--> <param name="inputName">downloadFile</param><!-- Specify the cache size of the downloaded file--> <param name="bufferSize">2048</param> </result> </action> </package></struts>A simple Struts2 multi-file upload and single-file download are implemented.
The above is all about this article, I hope it will be helpful to everyone's learning.