This article shares the specific implementation code for uploading and downloading of struts2 files for your reference. The specific content is as follows
1. File upload
Upload the file component submitted by struts,
front desk:
1) Submission method POST
2) Form type multipart/form-data
3) input type=file
Backstage:
FileUpload component provided by Apache
Core category:
FileItemFactory FileItem factory
ServletFileUpload core class for file upload in servlet
FileItem encapsulates the information of the uploaded form file items. In short, the file upload is more troublesome to process.
Struts' file upload <br />File upload interceptor helps us late file upload function
<interceptor name="fileUpload"/>
upload.xml
<struts> <package name="upload_" extends="struts-default"> <!-- Note: The keyword "fileUpload" cannot be used with the keyword "fileUpload" --> <action name="fileUploadAction"> <!-- Restrict the types of files uploaded --> <interceptor-ref name="defaultStack"> <!-- Restrict the extension of files running --> <param name="fileUpload.allowedExtensions">txt,jpg,jar</param> <!-- Restrict the types of files running [used at the same time as above, get intersection] <param name="fileUpload.allowedTypes">text/plain</param> --> </interceptor-ref> <result name="success">/e/success.jsp</result> <!-- Configuration error view--> <result name="input">/e/error.jsp</result> </action> </package> </struts>
upload.jsp
<body> <form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data"> Username:<input type="text" name="userName"><br/> File:<input type="file" name="file1"><br/> <input type="submit" value="upload"> </form> </body>error.jsp
<body> error.jsp<br/> <!-- View all error messages generated by the struts framework during runtime--> <%@ taglib uri="/struts-tags" prefix="s" %> <s:fielderror></s:fielderror> </body> success.jsp<body> success.jsp </body>
Core code
FileUpload .class
public class FileUpload extends ActionSupport { // Corresponding form: <input type="file" name="file1"> private File file1; // File name private String file1FileName; // File type (MIME) private String file1ContentType; public void setFile1(File file1) { this.file1 = file1; } public void setFile1FileName(String file1FileName) { this.file1FileName = file1FileName; } public void setFile1ContentType(String file1ContentType) { this.file1ContentType = file1ContentType; } @Override public String execute() throws Exception { /********* Get the uploaded file and process it*******/ // Upload the file to the upload directory// Get the uploaded directory path String path = ServletActionContext.getServletContext().getRealPath("/upload"); // Create the target file object File destFile = new File(path,file1FileName); // Copy the uploaded file to the target fileUtils.copyFile(file1, destFile); return SUCCESS; }} File upload processing details
a. File size limit
The maximum file upload supported by structs is 2M by default, and it is modified by constants:
<!-- 4. Modify the maximum size of uploaded files to 30M -->
<constant name="struts.multipart.maxSize" value="31457280"/>
b. Restrict the allowable type of uploaded files: Only file interceptors with txt/jpg suffixes are allowed: Inject parameters to limit file upload types
<!-- Restrict the type of file uploaded --> <interceptor-ref name="defaultStack"> <!-- Restrict the extension of file running --> <param name="fileUpload.allowedExtensions">txt,jpg,jar</param> <!-- Restrict the type of file running [used at the same time as above, get the intersection] <param name="fileUpload.allowedTypes">text/plain</param> --> </interceptor-ref>
2. Download the file
Struts file download, 2 ways:
Method 1: Write byte stream data to the browser through the response object; set the response header method for download 2: struts method
Download the struts file:
Copy the code as follows:<result-type name="stream"/>
First, please note that you create a new upload folder in the webroot directory and put the file you want to provide to the downloaded folder.
upload.xml
<action name="down_*" method="{1}"> <!-- List display--> <result name="list">/e/list.jsp</result> <!-- Download operation--> <result name="download" type="stream"> <!-- The type of file running download: Specified as all binary file types--> <param name="contentType">application/octet-stream</param> <!-- The corresponding attribute in Action: Return the property of the stream [actually getAttrInputStream()] --> <param name="inputName">attrInputStream</param> <!-- The download header, including: the file name displayed by the browser--> <param name="contentDisposition">attachment;filename=${downFileName}</param> <!-- Buffer Size Setting--> <param name="bufferSize">1024</param> </result> </action>list.jsp
<body> <table align="center"> <tr> <td>Number</td> <td>File name</td> <td>Operation</td> </td> <%@tglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:forEach var="fileName" items="${fileNames}" varStatus="vs"> <tr> <td>${vs.count }</td> <td>${fileName }</td> <td> <!-- Build a url --> <c:url var="url" value="down_down"> <c:param name="fileName" value="${fileName}"></c:param> </c:url> <a href="${url }">Download</a> </td> </tr> </c:forEach> </table> </body>DownAction
/** * File download* 1. Show the list of all files to be downloaded* 2. File download* */public class DownloadAction extends ActionSupport { /*******************1. Show the list of all files to be downloaded****************************/ public String list() throws Exception { //Get the upload directory path String path = ServletActionContext.getServletContext().getRealPath("/upload"); // Directory object File file = new File(path); //Get the file name of all files to be downloaded String[] fileNames = file.list(); // Save ActionContext ac = ActionContext.getContext(); // Get the map representing the request (the second way) Map<String,Object> request= (Map<String, Object>) ac.get("request"); request.put("fileNames", fileNames); return "list"; } /******************2. File download****************************/ // 1. Get the file name of the file to be downloaded private String fileName; public void setFileName(String fileName) { // Handle the problem in the passed parameters (get submission) try { fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } // Assign this.fileName = fileName; } //2. Download the submitted business method (configure the stream in struts.xml) public String down() throws Exception { return "download"; } // 3. Methods to return file stream public InputStream getAttrInputStream(){ return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName); } // 4. Download the displayed file name (filename displayed by the browser) public String getDownFileName() { // Chinese encoding is required try { fileName = URLEncoder.encode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return fileName; }}The above is all about this article, I hope it will be helpful to everyone's learning.