When working in B/S systems, it usually involves uploading files and downloading files. Before we connect to the struts2 framework, we use the FileUpload component of the commons subproject under apache to upload files. However, if we do that, the code looks cumbersome and inflexible. After learning struts2, struts2 provides a better implementation mechanism for file upload and download. Here I will explain the source code for single file upload and multi-file upload. Here we need to import two jar files uploaded by file download, one is commons-fileupload-1.2.2.jar, and the other is commons-io-2.0.1.jar.
Struts2 single file upload:
First of all, there is a jsp file upload page. This is relatively simple, it is a form with a file upload box.
<!--When uploading the file, the form submission method must be post, because the binary file may be very large when uploading the file. There is also the enctype attribute. This attribute must be written as multipart/form-data, otherwise it will be uploaded to the server in binary text--> <form action="fileUpload.action" method="post" enctype="multipart/form-data"> username: <input type="text" name="username"><br> file: <input type="file" name="file"><br> <input type="submit" value="submit"> </form>
Next is the FileUploadAction part of the code. Because struts2 provides a good internship mechanism for uploading and downloading, we only need to write very little code in action:
public class FileUploadAction extends ActionSupport{ private String username; //Note that file does not refer to the file itself uploaded by the front-end jsp, but the file uploaded to store it under the temporary folder private File file; //The name of the file submitted private String fileFileName; //The MIME type of the file submitted private String fileContentType; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFileContentType() { return fileContentType; } public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; } @Override public String execute() throws Exception { String root = ServletActionContext.getServletContext().getRealPath("/upload"); InputStream is = new FileInputStream(file); OutputStream os = new FileOutputStream(new File(root, fileFileName)); System.out.println("fileFileName: " + fileFileName); // Because file is a file stored in a temporary folder, we can print out its file name and file path to see if it is the same as the previous fileFileName System.out.println("file: " + file.getName()); System.out.println("file: " + file.getPath()); byte[] buffer = new byte[500]; int length = 0; while(-1 != (length = is.read(buffer, 0, buffer.length))) { os.write(buffer); } os.close(); is.close(); return SUCCESS; }}First of all, we need to be clear that the file here does not really refer to the file uploaded by jsp. When the file is uploaded, struts2 will first look for the storage location specified by struts.multipart.saveDir (this is in default.properties). We can create a new struts.properties property file to specify the temporary file storage location. If it is not specified, the file will be stored in tomcat's apache-tomcat-7.0.29/work/Catalina/localhost/ directory. Then we can specify the storage location after uploading the file, and just write it to the stream through the output stream. At this time, we can see the file we uploaded in the folder.
After uploading the file, we still need to download it. In fact, the principle of downloading struts2 is very simple. It is to define an input stream and then write the file into the input stream. The key configuration is still to configure it in the struts.xml configuration file:
The FileDownloadAction code is as follows:
public class FileDownloadAction extends ActionSupport{ public InputStream getDownloadFile() { return ServletActionContext.getServletContext().getResourceAsStream("upload/Address Book September 4, 2012.xls"); } @Override public String execute() throws Exception { return SUCCESS; }}Let's see that this action just defines an input stream and then provides it with a getter method. Next, let's take a look at the configuration file of struts.xml:
<action name="fileDownload"> <result name="success" type="stream"> <param name="contentDisposition">attachment;filename="Address Book September 4, 2012.xls"</param> <param name="inputName">downloadFile</param> </result> </action>
There are several things we need to pay attention to in the struts.xml configuration file. First of all, the type of result. In the past, we defined an action. We basically did not write the type attribute in the result, because it defaults to request forwarding (dispatcher). In addition to this attribute, there are generally values such as redirect (redirect). Here, because we are using file download, the type must be defined as stream type, telling the action. This is the result of the file download. There are generally param sub-elements in the result element. This is used to set the parameters when downloading the file. e This property is to get the file input stream in action. The name must be the same as the input stream attribute in action. Then the contentDisposition attribute is the contentDisposition attribute. This property is generally used to specify how we want to process the downloaded file. If the value is attachment, a download box will pop up, allowing the user to choose whether to download. If this value is not set, the browser will first check whether to open the downloaded file. If it can, it will directly open the downloaded file (of course, this is not what we need). Another value is filename, which is the file download name prompted by the file when downloading. After configuring this information, we can implement the file download function.
Struts2 multiple files upload :
In fact, the principle of multi-file upload is the same as single file upload. A single file upload is a single File, and a List<File> collection or a File[] array is uploaded. First, let’s take a look at the code of the front-end jsp part. Here I used jquery to implement dynamic file addition and dynamic delete download boxes:
<script type="text/javascript" src="script/jquery-1.8.1.js"></script> <script type="text/javascript"> $(function() { $("#button").click(function() { var html = $("<input type='file' name='file'>"); var button = $("<input type='button' name='button' value='delete'><br>"); $("#body div").append(html).append(button); button.click(function() { html.remove(); button.remove(); }) }) }) </script> </head> <body id="body"> <form action="fileUpload2.action" method="post" enctype="multipart/form-data"> username: <input type="text" name="username"><br> file: <input type="file" name="file"> <input type="button" value="add" id="button"><br> <div></div> <input type="submit" value="submit"> </form> </body> The names of files must be named files, and then the action code for uploading multiple files is as follows:
public class FileUploadAction2 extends ActionSupport{ private String username; // Here we use List to store uploaded files. File also refers to temporary files in temporary folders, rather than the actually uploaded files private List<File> file; //This List stores the name of the file, corresponding to the file in List<File> private List<String> fileFileName; private List<String> fileContentType; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public List<File> getFile() { return file; } public void setFile(List<File> file) { this.file = file; } public List<String> getFileFileName() { return fileFileName; } public void setFileFileName(List<String> fileFileName) { this.fileFileName = fileFileName; } public List<String> getFileContentType() { return fileContentType; } public void setFileContentType(List<String> fileContentType) { this.fileContentType = fileContentType; } @Override public String execute() throws Exception { String root = ServletActionContext.getServletContext().getRealPath("/upload"); for(int i = 0; i < file.size(); i++) { InputStream is = new FileInputStream(file.get(i)); OutputStream os = new FileOutputStream(new File(root, fileFileName.get(i))); byte[] buffer = new byte[500]; @SuppressWarnings("unused") int length = 0; while(-1 != (length = is.read(buffer, 0, buffer.length))) { os.write(buffer); } os.close(); is.close(); } return SUCCESS; }}This also writes it into an output stream, so that we can see multiple uploaded files in the folder
The next file download is exactly the same as the file download just now, and the same is struts.xml, so I won't repeat it here.
Summary: In general, the file upload and download mechanism provided by struts2 simplifies a lot of our code. We can use this mechanism in future projects. We can also use the FileUpload component to upload files. This is all determined by personal preferences!
There is only so much content about file upload and download functions in JavaWeb, thank you for your reading.