81,122
社区成员




package com.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UpLoadAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
//文件上传拦截器fileupload拦截器可以获取上传文件的 文件名和文件对象
//上传文件名
private String FileName;
//上传文件对象
private File file;
//获取struts.xml中配置文件的文件保存路径
private String savePath;
public String getFileName() {
return FileName;
}
public void setFileName(String fileName) {
FileName = fileName;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getSavePath() {
//由相对路径获得绝对保存路径
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public String execute() throws Exception{
//以服务器的文件保存地址和源文件名建立上传文件输出流,向里面写数据
FileOutputStream os=new FileOutputStream(getSavePath()+"\\"+getFileName());
//在上传文件对象上建立文件输入里对象,从文件对象里读数据
FileInputStream is=new FileInputStream(getFile());
byte[] buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))>0){
os.write(buffer, 0, len);
}
os.close();
is.close();
return SUCCESS;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="globalMessages_zh_CN"></constant>
<constant name="struts.i18n.encoding" value="utf-8"></constant>
<!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
<constant name="struts.multipart.saveDir " value="d:\temp" />
<package name="load" extends="struts-default">
<action name="UpLoad" class="com.action.UpLoadAction">
<!-- 文件上传拦截器配置 -->
<interceptor-ref name="fileUpload"><!-- 文件上传拦截器fileUpload要一模一样,否则就会出错!!! -->
<param name="maximumSize">1000000</param><!-- 设置上传文件最大字节数 -->
<param name="allowedTypes">image/jpg,image/x-png,image/gif,image/jpeg,image/pjpeg,image/bmp</param><!-- 设置上传文件类型 -->
</interceptor-ref>
<!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
<interceptor-ref name="defaultStack"/>
<!-- 设置上传文件的保存文件夹,向action属性注入的值也可以来自struts.xml中的action参数 -->
<!-- 动态设置savePath的属性值 -->
<param name="savePath">/save</param>
<result name="input">fileup.jsp</result>
<result name="success">fileupsuccess.jsp</result>
</action>
</package>
</struts>