First, upload a single file
Uploading files is a feature that many web programs have. A component for uploading files has been provided in struts1.x. In Struts2, a more easily manipulated upload file component is provided. The difference is that the struts1.x upload component needs a actionform to pass the file, and the Struts2 upload component is an interceptor (this interceptor is not configured and automatically loaded). In this article first introduced how to upload a single file with Struts2, the last introduction to use STRUTS2 upload any number of files.
The ability to upload a single file with Struts2 is very easy to implement, as long as the normal action can be used. But in order to get some information about uploading files, such as uploading file names, uploading file types and uploading stream objects, you need to add some getter and setter methods to the action class according to certain rules.
In Struts2, the method used to get and set the Java.io.File object (Struts2 upload the file to a temporary path and use Java.io.File to open the temporary file) is getupload and setupload. The way to get and set the file name is Getuploadfilename and Setuploadfilename, and the way to get and set the content type of uploading files is Getuploadcontenttype and Setuploadcontenttype. Here is the complete code for the action class for uploading:
package action; Import java.io.*; import com.opensymphony.xwork2.ActionSupport; public class Uploadaction extends A
Ctionsupport {private File upload;
Private String Uploadfilename;
Private String Uploadcontenttype;
Public String Getuploadfilename () {return uploadfilename;
public void Setuploadfilename (String fileName) {this.uploadfilename = filename;
Public File Getupload () {return upload;
The public void Setupload (File upload) {this.upload = upload;
public void Setuploadcontenttype (String contentType) {this.uploadcontenttype=contenttype;
Public String Getuploadcontenttype () {return this.uploadcontenttype; Public String Execute () throws Exception {Java.io.InputStream is = new Java.io.FileInputStream (Uploa
D);
Java.io.OutputStream OS = new Java.io.FileOutputStream ("d:\\upload\\" + uploadfilename); BytE buffer[] = new byte[8192];
int count = 0;
while ((count = is.read (buffer)) > 0) {os.write (buffer, 0, count);
} os.close ();
Is.close ();
return SUCCESS; }
}