File Upload
Preparing files
1. Upload a single file page
<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <%@ taglib prefix= "s" uri= "/struts-tags"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
2. Configure the appropriate action in the Struts.xml
<action name = "Upload" class= "action. Uploadaction "> <!--to save the directory by param parameter settings-- <param name=" Savepath ">/image</param> <result name= "Success" >/upload_success.jsp</result> </action>
3. Find the corresponding class based on the action node
Package Action;import Java.io.file;import Java.io.fileinputstream;import java.io.fileoutputstream;import Org.apache.struts2.servletactioncontext;import Com.opensymphony.xwork2.actionsupport;public class UploadAction Extends actionsupport{//encapsulate the properties of the uploaded files private file upload; The type of the encapsulated upload file private String uploadcontenttype; Encapsulates the name of the uploaded file private String uploadfilename; Public File Getupload () {return upload; } public void Setupload (File upload) {this.upload = upload; } public String Getuploadcontenttype () {return uploadcontenttype; } public void Setuploadcontenttype (String uploadcontenttype) {this.uploadcontenttype = Uploadcontenttype; } public String Getuploadfilename () {return uploadfilename; } public void Setuploadfilename (String uploadfilename) {this.uploadfilename = Uploadfilename; } public void Setsavepath (String savepath) {this.savepath = Savepath; }//Get file upload path to PRIVate String Savepath; @Override public String Execute () throws Exception {//create cache array byte [] buffer =new byte[1024]; Read file FileInputStream fis =new fileinputstream (Getupload ()); Save the file and set the path to save the directory FileOutputStream fos =new fileoutputstream (Getsavepath () + "\ \" +this.getuploadfilename ()); int length =fis.read (buffer); while (length>0) {//writes Fos.write (buffer,0,length) for length of each write; Length=fis.read (buffer); } fis.close (); Fos.flush (); Fos.close (); return SUCCESS; Public String Getsavepath () {return Servletactioncontext.getservletcontext (). Getrealpath (Savepath); }}
4. If successful, find a success page
<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <%@ taglib prefix= "s" uri= "/struts-tags"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Single File Upload