Upload. jsp
<% @ Page pageEncoding = "UTF-8" %>
Struts. xml:
<! -- This is an example of uploading a file to a small file --> <struts> <! -- Change the maximum limit of Struts2 File Upload --> <constant name = "struts. multipart. maxSize "value =" 5000000 "> </constant> <package name =" demo "namespace ="/demo "extends =" struts-default "> <! -- Go to the upload page Action --> <action name = "toUpload"> <result name = "success">/WEB-INF/upload. jsp </result> </action> <! -- Upload file Action --> <action name = "upload" class = "com.tar ena. action. UploadAction"> <interceptor-ref name = "fileUpload"> <! -- Change the File Upload restrictions of Action --> <param name = "maximumSize"> 2000000 </param> </interceptor-ref> <interceptor-ref name = "basicStack"> </ interceptor-ref> <result name = "success">/WEB-INF/OK. jsp </result> <result name = "error">/WEB-INF/error. jsp </result> </action> </package> </struts>
Action:
Public class UploadAction implements ServletContextAware {// enter the private File attribute some; private String someFileName; private ServletContext ctx; public String getSomeFileName () {return someFileName;} public void setSomeFileName (String someFileName) {this. someFileName = someFileName;} public File getSome () {return some;} public void setSome (File some) {this. some = some;} public String execute () {System. out. println ("SOME" + some); System. out. println ("FileName:" + someFileName); if (some = null) {return "error";} // 1. Based on the input attributes, build the storage path // specify the upload File name String name = "upload _" + someFileName; // construct a relative path String path = "upload/" + name; // construct the absolute path = ctx based on the relative path. getRealPath (path); System. out. println ("PATH:" + path); // 2. Copy the input attributes to FileUtil under the PATH based on the storage path. copy (some, new File (path); // 3. return the feature string and find Result return "success";} public void setServletContext (ServletContext SC) {ctx = SC ;}}
FileUtil. java: Provides File Replication
public class FileUtil { public static boolean copy(File src, File dest) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(src)); bos = new BufferedOutputStream(new FileOutputStream(dest)); byte[] bts = new byte[1024]; int len = -1; while ((len = bis.read(bts)) != -1) { bos.write(bts, 0, len); } return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
See http://www.blogjava.net/max/archive/2007/03/21/105124.html
This article from the "beautiful life needs to carefully record" blog, please be sure to keep this http://huing.blog.51cto.com/1669631/1287548