Next to the previous article:
2. File upload and download
Three tricks developed by Struts2, page jsp - configuration file struts2.xml - and action class action
File upload prerequisite:
The method of the form form must be post
The enctype of the form form must be multipart/form-data
Provide the upload input field of type="file"
Some rules for Struts support for file uploads
1. Single file upload
Development steps:
1) Add commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar under WEB-INF/lib. These two files can be downloaded from http://commons.apache.org/
2) Step 2: Write upfile.jsp, and set the enctype of the form table to: "multipart/form-data", as follows:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="/struts-tags" prefix="s"%><body> <s:actionerror/> <hr/> <s:fielderror></s:fielderror> <form action="${pageContext.request.contextPath}/upload1.action" method="post" enctype="multipart/form-data"><!-- Passing in MIME--> Username: <input type="text" name="username"/><br/> Beautiful photos: <input type="file" name="photo"/><br/> <input type="submit" value="upload"/> </form> </body>Write error page error.jsp
<body> The server is busy, try again after a while. </body>
success.jsp
<body> Upload successfully</body>
3) Write UploadAction1 class: Add attributes to the Action class, and the attributes correspond to the name of the file field in the form:
package com.itheima.actions;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;//File upload: public class UploadAction1 extends ActionSupport { private String username; private File photo;//Consistent with the upload field name of the form. The type is File type private String photoFileName;//Upload file name private String photoContentType;//Upload file MIME type//Omit getter and setter methods public String upload(){ System.out.println(photoFileName+":"+photoContentType); //Ordinary field: System.out.println(username); //Upload field: Upload to a folder. Save it to the application's images directory String realPath = ServletActionContext.getServletContext().getRealPath("/images"); File directory = new File(realPath); if(!directory.exists()){ directory.mkdirs(); } try { FileUtils.copyFile(photo, new File(directory, photoFileName)); return SUCCESS; } catch (IOException e) { e.printStackTrace(); return ERROR; } }}Add the following configuration to the struts.xml file
<action name="upload1" method="upload"> <interceptor-ref name="defaultStack"> <param name="fileUpload.allowedTypes">image/jpeg,image/png</param> <param name="fileUpload.allowedExtensionsSet">jpg,jpeg,png</param> </interceptor-ref> <result>/success.jsp</result> <result name="error">/error.jsp</result> <result name="input">/index.jsp</result></action>
Principle analysis:
a. The FileUpload interceptor is responsible for handling file upload operations. It is a member of the default defaultStack interceptor stack. The interceptor has 3 properties that can be set.
•maximumSize: The maximum length of the uploaded file (in bytes), the default value is 2 MB
• allowedTypes: The types that allow uploading files, separated by commas.
• allowedExtensions: Allows uploading file extensions. These 3 properties can be overwritten in struts.xml file by comma-separating each extension.
b. Uploading of files that exceed the size or illegally will cause an error (turn to an input view)
pass:
<s:actionError/> <s:feildError/> Tip to display error message
c. Change the error message prompt to Chinese version: With the help of international message resource files
If the error is caused by configuring global default parameters, it is best to use the global message resource file.
The default prompt resource file for struts2: struts-message.properties file of struts2-core-**.jar. Just compare the key value to overwrite the corresponding value.
The configuration is as follows:
struts.messages.error.uploading=Error uploading: {0}
struts.messages.error.file.too.large=File too large: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}
{0}: The value of the name attribute in <input type="file" name="uploadImage">
{1}: The real name of the uploaded file
{2}: The name of the upload file saved to the temporary directory
{3}: The type of uploaded file (for struts.messages.error.file.too.large is the size of uploaded file)
Source code:
Modify the information of the resource file that displays the error
Step 1: Create a new resource file such as fileuploadmessage.properties, place it under src to add the following information to the resource file
struts.messages.error.uploading=Uploading error: {0}
struts.messages.error.file.too.large=Upload file is too large: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=The type of uploaded file is not allowed: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=The suffix name of the uploaded file is not allowed: {0} "{1}" "{2}" {3}
Step 2: Load the resource file in the struts.xml file
<!-- Configure resource file for error information about uploading files-->
<constant name="struts.custom.i18n.resources" value="cn….xxx.fileuploadmessage"/>
2. Upload multiple files
Upload multiple files, you can use arrays or lists, and others are similar to single file uploads.
package com.itheima.actions;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;//File upload: public class UploadAction2 extends ActionSupport { private String username; private File[] photo;//Consistent with the upload field name of the form. Type is File type.array or List private String[] photoFileName;//Upload file name private String[] photoContentType;//Upload file MIME type public String upload(){ //Upload field: Upload to a folder. Save it to the application's images directory String realPath = ServletActionContext.getServletContext().getRealPath("/images"); File directory = new File(realPath); if(!directory.exists()){ directory.mkdirs(); } try { for(int i=0;i<photo.length;i++){ FileUtils.copyFile(photo[i], new File(directory, photoFileName[i])); } return SUCCESS; } catch (IOException e) { e.printStackTrace(); return ERROR; } }}3. File download
Principle: struts2 provides a stream result type, which is a specified stream result type specifically used to support file download function. It requires an inputName parameter to be specified. This parameter specifies an input stream and provides the entry to the downloaded file.
Coding steps:
1) Action class DownloadAction:
package com.itheima.actions;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.net.URLEncoder;import org.apache.commons.io.FilenameUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class DownloadAction extends ActionSupport { private InputStream image;//Use in the private String filename with problem;//File name private long filesize; public InputStream getImage() { return image; } public void setImage(InputStream image) { this.image = image; } public String getFilename() { return filename; } public long getFilesize() { return filesize; } public String download() throws Exception{ //Assign value to image byte stream String fileRealPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/classes/如.jpg"); filename = FilenameUtils.getName(fileRealPath); //Method 1: The Chinese file should be URL encoded// filename = URLEncoder.encode(filename, "UTF-8"); filesize = new File(fileRealPath).length(); System.out.println(filename); image = new FileInputStream(fileRealPath); return SUCCESS; }}struts.xml configuration file: mainly configure the results of stream type
<struts> <constant name="struts.devMode" value="true" /> <constant name="struts.ognl.allowStaticMethodAccess" value="true" /> <action name="download" method="download"> <result type="stream"> <param name="inputName">image</param><!--The field name of the InputStream in the action class needs to be provided in the Action, and return inputStream--> <param name="contentType">application/octet-stream</param><!--Tell the browser response header, the MIME format of the file, and call the getContentType method in Action--> <!-- Use OGNL expression in struts.xml to get the value of the property in the action class. Call getFilename() in the action class--> <!-- Chinese file name encoding: Method 2. Use OGNL expressions to call the static method of URLEncode--> <!-- Default OGNL calls static methods cannot be done. You need to turn on a constant switch.struts.ognl.allowStaticMethodAccess=true --> <param name="contentDisposition">attachment;filename=${@java.net.URLEncoder@encode(filename,'UTF-8')}</param><!-- Tell the browser how to download --> <param name="contentLength">${filesize}</param> </result> </action> </package></struts> The interceptor and file upload end here. It's so tiring, but full of accomplishment.
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.