Struts2上传文件

jsp:

 <form action="file_upload.action" method="post" enctype="multipart/form-data">
文件:<input type="file" name="myfile"/>
<input type="submit" value="上传"/>
</form>

action:

 package com.xyy.action;

 import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.Action; public class FileAction { private File myfile; //获取文件本身的数据
private String myfileFileName; //获取文件名称,变量名命名规则:域名(myfile)+"FileName"
private String myfileContentType; //获取文件类型,变量名命名规则:域名(myfile)+"ContentType" public void setMyfile(File myfile) {
this.myfile = myfile;
} public void setMyfileFileName(String myfileFileName) {
this.myfileFileName = myfileFileName;
} public File getMyfile() {
return myfile;
} public String getMyfileFileName() {
return myfileFileName;
} public String getMyfileContentType() {
return myfileContentType;
} public void setMyfileContentType(String myfileContentType) {
this.myfileContentType = myfileContentType;
} public String upload() throws IOException{
if(myfile != null && myfile.length() != 0){
//写入C盘权限不够的问题:以管理员身份运行eclipse
File destFile = new File("C:/"+myfileFileName);
FileUtils.copyFile(myfile, destFile);
return Action.SUCCESS;
}else{
System.out.println("文件为空!");
return Action.ERROR;
}
} }

struts.xml:

 <struts>
<!-- 配置常量 -->
<constant name="struts.configuration.xml.reload" value="true" /> <package name="upload-package" extends="struts-default">
<action name="file_*" class="com.xyy.action.FileAction" method="{1}">
<result>/upload_ok.jsp</result>
<result name="error">/upload_err.jsp</result>
</action>
</package>
</struts>
上一篇:object.assign()方法的使用


下一篇:NOIP2016DAY1题解