文件上传使用<s:file>标签,表单的method为post,enctype为multipart/form-data
<s:form action="SupplyAdd" method="post" theme="simple" enctype="multipart/form-data">
<s:file name="productImage"/>
</s:form>
<s:file name="xxx"/>对应的action里xxx、xxxContentType和xxxFileName三个属性
action内容
package com.platform.Action.Supply_Demand;
import java.io.File;
import java.util.Date;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.platform.Bean.SupplyInfo;
public class SupplyAddAction extends ActionSupport
{
private File productImage; //图片对象
private String productImageFileName;
public void setProductImage(File productImage)
{
this.productImage = productImage;
}
public String getProductImageFileName()
{
return productImageFileName;
}
public void setProductImageFileName(String productImageFileName)
{
this.productImageFileName = productImageFileName;
}
public String execute() throws Exception
{
//得到文件拓展名
int pos = productImageFileName.lastIndexOf(".");
String extention = productImageFileName.substring(pos);
String targetDirectory = ServletActionContext.getServletContext().getRealPath("/UploadFile");
String targetFileName = new Date().getTime() + extention;
File target = new File(targetDirectory,targetFileName);
FileUtils.copyFile(productImage, target);
return "success";
}
}
struts.xml 配置
<package name="Supple" extends="struts-default"> <action name="SupplyAdd" class="com.platform.Action.Supply_Demand.SupplyAddAction"> <interceptor-ref name="defaultStack"> <!-- 配置允许上传的文件类型,多个用","分隔 --> <param name="fileUpload.allowedTypes"> image/bmp,image/png,image/gif,image/jpeg </param> <!-- 配置允许上传的文件大小,单位字节 --> <param name="fileUpload.maximumSize">1048576</param> </interceptor-ref> <result name="input">WEB-INF/Platform/Supply_Demand/Supply_Add.jsp</result> <result name="toAdd">WEB-INF/Platform/Supply_Demand/Supply_Add.jsp</result> <result name="success">WEB-INF/Platform/Supply_Demand/Supply_Manage.jsp</result> </action> </package>
控制台出现 信息: Removing file productImage \Files\upload_48b62f95_128fc83187b__8000_00000162.tmp
struts.multipart.saveDir没有配置。struts.multipart.saveDir用于指定存放临时文件的文件夹,该配置写在struts.properties文件中。例如,如果在struts.properties文件加入如下代码:
struts.multipart.saveDir
=
/tmp
这样上传的文件就会临时保存到你根目录下的tmp文件夹中(一般为c:\tmp),如果此文件夹不存在,Struts 2会自动创建一个。