标签:
文件上传的时候struts会使用默认18个拦截器中的<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>进行处理。
文件上传Action类:
Action类中定义三个属性:
private File file1; 对应表单:<input type="file" name="file1">
private String file1FileName; 文件名
private String file1ContentType;文件的类型(MIME)
并且提供这三个属性的set方法。
文件上传表单:
<form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="userName"><br/> 文件:<input type="file" name="file1"><br/> <input type="submit" value="上传"> </form>
package cn.itcast.upload; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport{ // 对应表单:<input type="file" name="file1"> private File file1; // 文件名 private String file1FileName; // 文件的类型(MIME) private String file1ContentType; public void setFile1(File file1) { this.file1 = file1; } public void setFile1FileName(String file1FileName) { this.file1FileName = file1FileName; } public void setFile1ContentType(String file1ContentType) { this.file1ContentType = file1ContentType; } public String upload() throws IOException{ //得到上传的文件夹 String path=ServletActionContext.getServletContext().getRealPath("/upload"); //创建文件 File file=new File(path,file1FileName); //讲上传的文件上传到指定的文件夹 FileUtils.copyFile(file1, file); return "success"; } }struts.xml文件的配置:
<struts> <package name="upload_" extends="struts-default"> <!-- 注意: action 的名称不能用关键字"fileUpload" --> <action name="fileUploadAction" class="cn.itcast.upload.UploadAction" method="upload"> <result name="success">/index.jsp</result> <!-- 配置错误视图 --> <result name="input">/error.jsp</result> </action> </package> </struts>
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014010769/article/details/47035109