标签:
前台from表单;
<form action="dd.action" method="post"enctype="multipart/form-data">
</form>
表单在提交数据的时候以二进制流的形势向服务器提交数据;
struts2在原有的上传解析器继承上做了进一步封装,更近一步简化了文件上传;
struts2默认使用的是Jakarta和Common-FileUpload的文件上传框架,因此,如果需要shiyong
struts2的文件上传功能,则需要在web应用中导入相关的jar包;
后台的Action如何写;
(1)类型为File的xxx属性封装了该文件域对应的文件内容;import java.io.File;
(2)类型为String的XXXFileName属性封装了该案文件域对应的文件类型;
(3)类型为String的xxxContType属性封装了该文件对应的文件类型;
1.把下载好的struts的框架打开;
打开这个文件夹,把里面的空项目里的WEB-INF下的lib的jar复制到自己项目下的WEB-INF的文件
下。,在budlidpath -> add buildpath 加载jar的操作就完成了
2.还要把空项目下的src的struts.xml复制到,我们项目下的src目录下,把package中的内容删了
还有后面的内容也删了。
基本的配置就到这里;
前台页面;
<%@ page contentType="text/html;charset=utf-8" pageEncoding="UTF-8"%>
<form action="dd.action" method="post"enctype="multipart/form-data">
<table id="imageupload">
<tr height="30px" >
<td colspan="2">
【上传照片】
</td>
</tr>
<tr>
<td align="center">选择照片</td>
<td><input type="file" name="upload" size="50" /></td>
</tr>
<tr>
<td align="center">照片名</td>
<td><input type="text" name="info" size="50" /></td>
</tr>
<tr height="30">
<td colspan="2" align="center">
<input type="submit" value="上传" class="btn_bg"/>
<input type="reset" value="重置" class="btn_bg"/>${result}
</td>
</tr>
</table>
</form>
后台处理的action;
在项目的src中,创建一个包,在包里创建action
package com.test.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Fileaction extends ActionSupport {
private File upload;
private String uploadContType;
private String uploadFileName;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContType() {
return uploadContType;
}
public void setUploadContType(String uploadContType) {
this.uploadContType = uploadContType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String execute() throws Exception{
String path = ServletActionContext.getServletContext().getRealPath("/userfiles/images");
File file = new File(path);
System.out.print(file.exists());
if(!file.exists()){
file.mkdir();
System.out.println("建立文件夹");
}
FileUtils.copyFile(upload, new File(file,uploadFileName));
System.out.print("上传承购与否");
return SUCCESS;
}
}
剩下最后一步了,就是配置struts,
<action name="dd" class="com.test.action.Fileaction"> //这个class路径是action路径;
<result name="success">/index.jsp</result>
<result name="input">/error.jsp</result>
<interceptor-ref name="fileUpload">
<!-- 配置拦截器限制上传文件类型及大小 -->
<param name="allowedTypes">image/bmp,image/x-png,image/gif,image/jpeg</param>
<param name="maximumSize">2M</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
标签:
原文地址:http://www.cnblogs.com/zht0915/p/4638229.html