Upload of "Struts2" file and control of upload permission

Source: Internet
Author: User

There are a lot of articles about STRUTS2, which are described in detail, but the examples in the procedure are poorly written. A variety of meaningless interceptor technology, internationalization technology, initialization parameters, the original simple program made very cumbersome. At the same time, some of the key code is not written. Causes each upload Tomcat to report unable to find ' struts.multipart.saveDir ' property setting. Then upload a large file, the entire Web project crashes, and then the background throws a large segment of file Upload basesize Limit exceeded exception exception, the brush bursts tomcat. In fact, these warnings and exceptions can be avoided. I think the program should be shorter and more plump than elegant. Here is an example to illustrate.


I. BASIC OBJECTIVES

Using STRUTS2 to create a file upload system, limit only upload less than 2M of images, upload the success of the image of the Chinese name, size, and the original image display. This picture is saved to the server's upload folder. At the same time, throw a large file to this system, no server can be found.



II. Basic Preparation

With "Struts2" Struts2 Pure manual installation, configuration and HelloWorld, with the latest version of Struts 2.3.20 GA Example (click the Open link) as well as ready to Struts2 the necessary jar, and write good web. That's not an explanation. Every time I say Struts2, I have to quote this article. No additional packages are introduced this time.


After configuring the STRUTS2, the directory structure is as follows, create a new two folders inside, one is the future to store the upload file upload, a Struts2 required to upload the temporary folder tmp, this TMP can not, but will not stop reporting unable to find ' Warning of Struts.multipart.saveDir ' property setting. When writing a program, there is no need to write anything.


Third, the production process

1, the first is upload.jsp, nothing to say, is a document form. Just want people to notice to set the name of the file domain, a moment Struts2 to accept the file according to this name, here is the filename.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

2, uploaderr.jsp upload Failure page, this is mainly the output background through the error message. ErrMsg Direct use of the El expression of the Jsp2.4 can be, in the "filter" Filter filter to solve the post transmission encoding problem and the use of El Expression simplified parameter passing "(click Open link) has been mentioned. Do not like "Servlet" using Servlet3.0 Standard and JSTL expression to implement file upload system, support image upload display "(click Open link) to use the C tag, that is, jstl expression, not to use struts's s tag, take a small value, not so complex.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

3, upload the success of the page uploadsuc.jsp, the same can be taken out of the server on the save name to construct the image address, the background of the file name, size, the server saved file name is basically a time stamp, it is impossible to give you the Chinese name, But even if you want to save the Chinese name to read this picture is no problem, but to use the "Struts2" Chinese file download and download permissions control (click to open the link) technology

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

4, Struts.xml, although the file is involved, but as usual to specify the processing action is the Java file, set according to the results of the return to jump to what link. Because there is no need to throw documents back to the front desk. The main is to set two properties at the beginning to prevent Tomcat from throwing an exception. Also do not like some books, articles, such as the setting of the interceptor, initialization parameters, the slightest meaning. will only increase your memory burden.

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "Http://struts.apach E.org/dtds/struts-2.0.dtd "><struts><!--just to prohibit the upload when the warning pops up without temporary upload folder! In fact, this temporary upload folder can not be uploaded. I don't know what it's for. --><constant name= "Struts.multipart.saveDir" value= "/tmp"/><!--just set the size of struts throw file too large exception, here set to 4G, Because FAT32 the largest single file is 4gstruts2 the default throw file too large exception size of 2097152B is exactly 2M, more than this number will be in Tomcat spit a bunch of anomalies, and then the front desk display can not find the page, very unfriendly. File size control should not take advantage of throwing exception control, we ourselves in the Java file control can be--><constant name= "struts.multipart.maxSize" value= "4294967296"/> <!--in the test package--><package name= "test" extends= "Struts-default" ><!-- The action for upload is executed by the Run method in the Upload.java in the test package--><action name= "upload" class= "test.upload" method= "Run" > <result name= "Success" >/uploadsuc.jsp</result><result name= "error" >/uploaderr.jsp</result ></action></package></struts> 

5, Upload.java This is our core processing Java, contrast and "Servlet" using Servlet3.0 Standard and JSTL expression to implement file upload system, support image upload display " (Click the Open link) to take advantage of a part object processing all things Servlet3.0 file upload, Struts2 file upload, you must set a name and the foreground page to pass over the page the same files object. The name= "file" of the file object is upload.jsp. Therefore, there is a static class member for the file file. After that, STRUTS2 will automatically generate a filefilename, which is the file Domain Name property +filename, to wrap the file name passed by the user, note that n must be capitalized. Of course there is a string object named property +contenttype that gives you the encapsulation file type, but does not have to use this object at all, you can determine the file type according to the suffix name in filename. File.length () can then remove the file size.

Well, this allows you to control the upload permissions for the file. Struts2 also wants us to write our own method of storing the file in the server. There is no explanation for this piece of stuff. This is how the Java storage file is stored.

The package test;//uses the input stream and must support import java.io.*;//This is to take out the absolute path of the Upload folder import org.apache.struts2.servletactioncontext;//This is Struts2 necessary support import com.opensymphony.xwork2.actionsupport;// Prevent the serial number warning @suppresswarnings ("serial")//struts2 must inherit this class public class upload extends Actionsupport {// Upload file action intrinsic two properties Filecontenttype is not required//But be sure to set up getter and setter, which is inherent in Struts2 characteristics. Set up getter and setter must not be initialized in the execution method again, such as String xx=//so the foreground will not be worth! The private file File;private String Filefilename;//savefilename is the name saved to the server//using the suffix name + timestamp structure of the transmitted file, or, if necessary, the user name private String savefilename;//This is the size of the file, mainly for uploading to the foreground private string Filelength;private string errmsg;// Prevent input and output stream alert @suppresswarnings ("resource") public String Run () throws Exception {///To Give "" value to error message string, otherwise it will return to the foreground a nullerrmsg = "" ;//Determine if the condition of the upload is the boolean canupload = true;//take out the absolute path of the upload string savefilepath = Servletactioncontext.getservletcontext () . Getrealpath ("/upload");//Remove the suffix name of the uploaded file string fileextensions = Getfilefilename (). substring (Getfilefilename (). LastIndexOf (".")); /According to the suffix name to determine if you can upload if (! ( Fileextensions. Equals (". gif") | | Fileextensions.equals (". png") | | Fileextensions.equals (". jpeg") | | Fileextensions.equals (". jpg") | | Fileextensions.equals (". bmp"))) {errmsg + = "The upload file can only be a picture, the suffix name must be bmp,gif,jpg,jpeg! "; canupload = false;} Determine if the file size can be uploaded if (file.length () > (2 * 1024x768) {errmsg + = "Upload file is too large, please less than 2m! "; canupload = false;} Convert file size to string, push back to foreground filelength = (file.length ()/1024x768) + "KB";//If you can upload if (canupload) {//Create a file name on the server Savefilename = The System.currenttimemillis () + fileextensions;//output stream is the output stream saved to the server FileOutputStream fos = new FileOutputStream (savefilepath + "/" + savefilename);//input stream is the file passed FileInputStream fis = new FileInputStream (GetFile ());//buffer array byte[] buffer = new byte[ 1024];int len = 0;//input stream reads the buffer array until it finishes reading while (len = fis.read (buffer)) > 0) {// The output stream keeps a buffer array of things written to the server on the upload absolute directory above fos.write (buffer, 0, Len);} Return struts.xml A successful result return "Success";} else {return "error";}} All static members must have getter and setter, otherwise they cannot interact with the foreground 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 GetSaveFileName () {return savefilename;} public void Setsavefilename (String savefilename) {this.savefilename = Savefilename;} Public String geterrmsg () {return errmsg;} public void Seterrmsg (String errmsg) {this.errmsg = errmsg;} Public String Getfilelength () {return filelength;} public void Setfilelength (String filelength) {this.filelength = Filelength;}}


Upload of "Struts2" file and control of upload permission

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.