File upload and download examples for Struts2 in java
- 2020-05-19 04:51:57
- OfStack
File upload
multipart/form-data
The method property of the HTML form must be set to post
Need to add
<input type=“file”>
Field.
Struts support for file uploads
In the Struts application, the FileUpload interceptor and the Jakarta Commons FileUpload components can upload files.
Steps:
Use the file tag in the file upload form on the Jsp page. If you need to upload more than one file at a time, you must use multiple file tags with the same name
Add three new file upload properties to Action. The names of these properties must be in the following format
Basic file upload: directly define the following three properties in Action and provide the corresponding getter and setter
[File Name] : type -File - uploaded file. For example: data (fileName requirements and name1 for file form items)
[File Name]ContentType: type -String - file type for uploaded files. For example: dataContentType (used to receive file types (MIME values))
[File Name]FileName: String - file name of the uploaded file. For example: dataFileName (the name used to receive the file)
If you upload multiple files, you can use List
If multiple files are passed, the above three properties can be changed to List type! The name attribute value for multiple file fields requires 1.
The sample code
<s:form action="testUpload" enctype="multipart/form-data">
<s:textfield name="userName[0]" label=" The user -1"></s:textfield>
<s:file name="photos" label=" photo "></s:file>
<s:textfield name="userName[1]" label=" The user -2"></s:textfield>
<s:file name="photos" label=" photo "></s:file>
<s:textfield name="userName[2]" label=" The user -3"></s:textfield>
<s:file name="photos" label=" photo "></s:file>
<s:submit value=" submit "></s:submit>
</s:form>
public class UploadAction extends ActionSupport{
@Setter@Getter
private List<File> photos;
@Setter@Getter
private List<String> photosContentType;
@Setter@Getter
private List<String> photosFileName;
@Setter@Getter
private List<String> userName;
public String testUpload() throws IOException {
System.out.println("userName: "+userName);
System.out.println("photos: "+photos);
System.out.println("photosFileName: "+ photosFileName);
System.out.println("photosContentType: "+photosContentType);
// Upload the file to the server root upload Under the file
// To obtain ServletContext
ServletContext servletContext = ServletActionContext.getServletContext();
// Get the real path
String realPath = servletContext.getRealPath("/upload");
System.out.println(realPath);
File uploadFile = new File(realPath);
// Determine if the path exists
if (!uploadFile.exists()){
// There is no creation
uploadFile.mkdir();
}
for (int i = 0; i < photos.size(); i++) {
UUID uuid = UUID.randomUUID();
FileUtils.copyFile(photos.get(i), new File(realPath + "/" + uuid + photosFileName.get(i)));
}
return SUCCESS;
}
}
1. Deal with a few small problems?
1. Duplicate the name of the file name, 1 can be generated in front of the file name 1 UUID as a prefix.
Limit the size of a single file
3. Limit file types
4. Limit the total file size
2. The FileUpload interceptor is provided in Struts2 to set these property values for us
The FileUpload interceptor has three properties that can be set.
maximumSize: maximum length (in bytes) for uploading a single file, with a default value of 2 MBallowedTypes: types of files that are allowed to be uploaded, separated by commas allowedExtensions: allows file extensions to be uploaded, separated by commas These three properties can be overridden in the struts.xml file
Note: default.properties under org.apache.struts2 has a limit on the total size of the uploaded file. This limit can be modified using constants struts.multipart.maxSize =2097152
<constant name="struts.devMode" value="true"/>
<!-- Modify the size of the total file here -->
<constant name="struts.multipart.maxSize" value="2097152"/>
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor-stack name="myInterceptor">
<interceptor-ref name="defaultStack">
<!-- Modify the size of a single file, Commons FileUpload By default, the component accepts the maximum number of uploaded files 2M -->
<param name="fileUpload.maximumSize">57,408</param>
<!-- Type of file allowed for upload -->
<param name="fileUpload.allowedTypes">image/pjpeg,image/gif</param>
<!-- An extension that allows you to upload files -->
<param name="fileUpload.allowedExtensions">jpg,gif</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myInterceptor"></default-interceptor-ref>
<action name="testUpload" class="org.pan.action.UploadAction" method="testUpload">
<result name="success">/WEB-INF/views/success.jsp</result>
<result name="input">/upload.jsp</result>
</action>
</package>
1. Error messages about uploading files?
1. Error messages related to file upload are predefined in the struts-messages.properties file.
2. You can upload the corresponding Action resource file in the file or redefine the error message in the i18n_zh_CN.properties internationalization resource file
struts.messages.error.file.too.large= The file you sent is too big
struts.messages.error.content.type.not.allowed= File type error
struts.messages.error.file.extension.not.allowed= Extension error
struts.messages.upload.error.SizeLimitExceededException= The total file size exceeds the upper limit
File download
In some applications, you may need to dynamically send a file to the user's browser, and the name and location of the file are not known programmatically
Stream result type Struts provides one Stream result type specifically for file downloads. When using one Stream result, you do not need to prepare one JSP page. The Stream result type can be set with the following parameters: contentType: the MIME type of the downloaded file. The default value is text/plain contentLength: size of downloaded file in bytes contentDisposition: you can set the ContentDispositon response header for the download file name. The default value is inline, usually in the following format: attachment;filename="document.pdf". inputName: the input stream for the files provided in Action. The default value is inputStream bufferSize: the size of the buffer when the file is downloaded. The default value is 1024 allowCaching: is caching allowed when the file is downloaded? The default value is true contentCharSet: character encoding for file download. The above parameters can be provided in Action as the getter method!Parameters of the Stream result type can be overridden as attributes in Action Use specific details see struts - 2.3.15.3 - all/struts - 2.3.15.3 / docs/WW docs/stream - result. html
The sample code
<a href="testDownLoad"> download </a>
public class DownLoadAction extends ActionSupport{
// Usually the following parameters will be in Action Provided in the
@Setter@Getter
private String contentType;
@Setter@Getter
private long contentLength;
@Setter@Getter
private String contentDisposition;
@Setter@Getter
private InputStream inputStream;
public String testDownLoad() throws FileNotFoundException, UnsupportedEncodingException {
// To obtain ServletContext
ServletContext servletContext = ServletActionContext.getServletContext();
// Gets the path to the file
String realPath = servletContext.getRealPath("/WEB-INF/file/ At least you are. .mp3");
// Gets the flow of the file
inputStream = new FileInputStream(realPath);
// Sets the type of the file
contentType = servletContext.getMimeType(realPath);
// Gets the length of the file
contentLength = new File(realPath).length();
// Set file name
String fileName = " At least you are. .mp3";
fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
contentDisposition = "attachment;filename="+fileName;
return SUCCESS;
}
}
<!-- File download -->
<action name="testDownLoad" class="org.pan.action.DownLoadAction" method="testDownLoad">
<result type="stream">
<!-- File buffer size -->
<param name="bufferSize">2048</param>
</result>
</action>