Struts2 文件上传
1.文件上传Action类
package com.zhanggaosong.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String picName;
private File pic; // 上传文件的文件本身
private String picFileName; // 上传文件的原始文件名
private String picContentType; // 上传文件的文件类型
public String getPicName() {
return picName;
}
public void setPicName(String picName) {
this.picName = picName;
}
public File getPic() {
return pic;
}
public void setPic(File pic) {
this.pic = pic;
}
public String getPicFileName() {
return picFileName;
}
public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}
public String getPicContentType() {
return picContentType;
}
public void setPicContentType(String picContentType) {
this.picContentType = picContentType;
}
@Override
public String execute() throws Exception {
/**
* 处理文件上传
*/
String uploadPath = ServletActionContext.getServletContext()
.getRealPath("/upload");
String fileName = UUID.randomUUID().toString()
+ picFileName.substring(picFileName.lastIndexOf("."));
System.out.println(uploadPath + "/" + fileName);
System.out.println("文件名:"+fileName);
FileInputStream is = new FileInputStream(pic);
FileOutputStream os = new FileOutputStream(uploadPath + "/" + fileName);
byte[] buff = new byte[1024];
int hasRead = 0;
while((hasRead = is.read(buff))>0){
os.write(buff,0,hasRead);
}
is.close();
os.close();
/**
* 将文件名放到数据库中去
*/
return SUCCESS;
}
}
2.配置Struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="uploadAction" namespace="/" extends="struts-default">
<action name="uploadAction" class="com.zhanggaosong.action.UploadAction">
<result>/success.jsp
</result>
</action>
</package>
</struts>
3.文件上传页面
<body>
<h2>文件上传</h2>
<s:actionmessage />
<s:form action="uploadAction" method="post"
enctype="multipart/form-data">
<table>
<tr>
<td><s:file name="pic" label="请选择上传的文件:" /></td>
</tr>
<tr>
<td><s:submit value="上传" /></td>
</tr>
</table>
</s:form>
</body>