jsp:
1 <form action="file_upload.action" method="post" enctype="multipart/form-data"> 2 文件:<input type="file" name="myfile"/> 3 <input type="submit" value="上传"/> 4 </form>
action:
1 package com.xyy.action; 2 3 import java.io.File; 4 import java.io.IOException; 5 import org.apache.commons.io.FileUtils; 6 import com.opensymphony.xwork2.Action; 7 8 public class FileAction { 9 10 private File myfile; //获取文件本身的数据 11 private String myfileFileName; //获取文件名称,变量名命名规则:域名(myfile)+"FileName" 12 private String myfileContentType; //获取文件类型,变量名命名规则:域名(myfile)+"ContentType" 13 14 public void setMyfile(File myfile) { 15 this.myfile = myfile; 16 } 17 18 public void setMyfileFileName(String myfileFileName) { 19 this.myfileFileName = myfileFileName; 20 } 21 22 public File getMyfile() { 23 return myfile; 24 } 25 26 public String getMyfileFileName() { 27 return myfileFileName; 28 } 29 30 public String getMyfileContentType() { 31 return myfileContentType; 32 } 33 34 public void setMyfileContentType(String myfileContentType) { 35 this.myfileContentType = myfileContentType; 36 } 37 38 public String upload() throws IOException{ 39 if(myfile != null && myfile.length() != 0){ 40 //写入C盘权限不够的问题:以管理员身份运行eclipse 41 File destFile = new File("C:/"+myfileFileName); 42 FileUtils.copyFile(myfile, destFile); 43 return Action.SUCCESS; 44 }else{ 45 System.out.println("文件为空!"); 46 return Action.ERROR; 47 } 48 } 49 50 }
struts.xml:
1 <struts> 2 <!-- 配置常量 --> 3 <constant name="struts.configuration.xml.reload" value="true" /> 4 5 <package name="upload-package" extends="struts-default"> 6 <action name="file_*" class="com.xyy.action.FileAction" method="{1}"> 7 <result>/upload_ok.jsp</result> 8 <result name="error">/upload_err.jsp</result> 9 </action> 10 </package> 11 </struts>