对于struts2文件上传之前写过一个,是通过struts.properties的配置实现的,现在将配置信息改到了struts.xml中,一样可以成功了。
实现对文件上传类型,文件大小上限,保存文件绝路路径参数注入action。
上传jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>发微博</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body style="font-size:14px;">
<h2>写微博 <a href="index.jsp">返回首页</a></h2>
<form action="upload" method="post" enctype="multipart/form-data">
<textarea name="sayMessage" rows="4" cols="50"></textarea><br>
发文件<input name="upload" type="file"/><input type="submit" value="发微博">
</form>
<s:fielderror></s:fielderror>
</body>
</html>
struts2.xml文件中顶部常量配置部分:
<!-- 配置文件上传时临时文件存放路径,我测试的过程中没配,报错说该项为空。 -->
<constant name="struts.multipart.saveDir" value="E:\UploadFileDemo\tmp"></constant>
<!-- 设置上传大小上限:200M -->
<constant name="struts.multipart.maxSize" value="209715200"></constant>
<!-- 指定资源文件 -->
<constant name="struts.custom.i18n.resources" value="ApplicationResource"></constant>
struts2.xml文件中action部分:
<action name="upload" class="myFileUploadAction">
<result name="success">/index.jsp</result>
<result name="input">/saymessage.jsp</result>
<!--struts2默认只能上传2M文件,类型不限。 配置拦截器来限制上传文件的类型和大小 -->
<interceptor-ref name="fileUpload">
<!-- 限定文件上传类型 -->
<param name="allowedTypes">image/png,image/x-png,image/jpg,image/pjpeg,image/bmp,image/gif</param>
<!-- maximumSize指每个上传文件的大小上限,单位为:byte,这里设为30M,该值不能大于struts.multipart.maxSize总大小 -->
<param name="maximumSize">31457280</param>
</interceptor-ref>
<!-- 默认拦截器栈 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 注入文件上传路径参数到myFileUploadAction中 -->
<param name="savePath">E:\\UploadFileDemo</param>
</action>
文件上传action代码:
package com.gifer.action;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import com.gifer.model.LoginUser;
import com.gifer.model.SayFiles;
import com.gifer.model.SayMessage;
import com.gifer.service.SayMessageService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUpLoadAction extends ActionSupport {
private static final long serialVersionUID = -1232100382633301276L;
private static final Logger log = Logger.getLogger(FileUpLoadAction.class);
// 微博内容
private String sayMessage;
// 上传多个文件的集合文本
private List<File> upload;
// 多个上传文件的类型集合
private List<String> uploadContextType;
// 多个上传文件的文件名集合
private List<String> uploadFileName;
// 文件存放路径根目录
private String savePath;
private SayMessageService sayMessageService;
public String getSayMessage() {
return sayMessage;
}
public void setSayMessage(String sayMessage) {
this.sayMessage = sayMessage;
}
public List<File> getUpload() {
return upload;
}
public void setUpload(List<File> upload) {
this.upload = upload;
}
public List<String> getUploadContextType() {
return uploadContextType;
}
public void setUploadContextType(List<String> uploadContextType) {
this.uploadContextType = uploadContextType;
}
public List<String> getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}
/**
* 从配置文件注入文件根目录参数,绝对路径
*
* @param savePath
*/
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public void setSayMessageService(SayMessageService sayMessageService) {
this.sayMessageService = sayMessageService;
}
@Override
public String execute() throws Exception {
try {
// 把上传的文件放到指定的路径下 取相对路径
// savePath = ServletActionContext.getServletContext().getRealPath(
// "/WEB-INF/uploadfiles");
Calendar myDate = Calendar.getInstance();
int intYear = myDate.get(Calendar.YEAR);
int intMonth = myDate.get(Calendar.MONTH) + 1;
int intDate = myDate.get(Calendar.DATE);
// 一律使用'/'以兼容windows和linux操作系统路径
// 文件url相对路径
String relativeUrl = "Files/" + intYear + "/" + intMonth + "/"
+ intDate + "/";
// 文件保存绝对路径
savePath += "/" + intYear + "/" + intMonth + "/" + intDate;
// 文件保存目录
File files = new File(savePath);
// 如果指定的路径没有就创建
if (!files.exists()) {
files.mkdirs();
}
// 组织成微博实体对象
SayMessage sayMessage = new SayMessage();
sayMessage.setSayContent(this.getSayMessage());
Timestamp sayTime = new Timestamp(System.currentTimeMillis());
sayMessage.setSayTime(sayTime);// 当前时间
LoginUser sayUser = (LoginUser) ActionContext.getContext()
.getSession().get("user");// 从session中获取用户信息
sayMessage.setSayUser(sayUser.getUserId());
Set sayFiles = new HashSet();
// 把得到的文件的集合通过循环的方式读取并放在指定的路径下
for (int i = 0; i < upload.size(); i++) {
try {
SayFiles sayFile = new SayFiles();
String oldFileName = uploadFileName.get(i);// 上传文件原名
// 生成随机文件名:当前年月日时分秒+五位随机数(为了在实际项目中防止文件同名而进行的处理)
Random r = new Random();
int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数
SimpleDateFormat sDateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss"); // 时间格式
String nowTimeStr = sDateFormat.format(new Date()); // 当前时间字符串
String extName = "";
// 获取拓展名
if (oldFileName.lastIndexOf(".") >= 0) {
extName = oldFileName.substring(oldFileName
.lastIndexOf("."));
}
// 新文件名
String newFileName = nowTimeStr + rannum + extName;
relativeUrl += newFileName;// 文件保存到数据库中的相对路径
// list集合通过get(i)的方式来获取索引
// 将文件逐一复制到指定目录
FileUtils.copyFile(upload.get(i), new File(files,
newFileName));
sayFile.setFileName(oldFileName);
sayFile.setFileUrl(relativeUrl);
sayFile.setUploadTime(sayTime);
sayFile.setSayMessage(sayMessage);
sayFiles.add(sayFile);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
sayMessage.setSayFileses(sayFiles);
this.sayMessageService.save(sayMessage);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException();
}
return SUCCESS;
}
}
ApplicationResource.properties资源文件
#Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net)
login.user.password = \u5BC6\u7801
login.user.password.invalid = \u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A
login.user.userId = \u7528\u6237\u540D
login.user.userId.invalid = \u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A
#\u66F4\u6539\u4E0A\u4F20\u6587\u4EF6\u7C7B\u578B\u4E0D\u5141\u8BB8\u7684\u63D0\u793A\u4FE1\u606F
struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6\u7C7B\u578B\u4E0D\u88AB\u5141\u8BB8
#\u66F4\u6539\u4E0A\u4F20\u6587\u4EF6\u592A\u5927\u7684\u63D0\u793A\u4FE1\u606F
struts.messages.error.file.too.large=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u4E0A\u9650\uFF0830M\uFF09
#\u6587\u4EF6\u4E0A\u4F20\u5176\u5B83\u9519\u8BEF\u4FE1\u606F
struts.messages.error.uploading=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u4E0A\u4F20\u7A0B\u5E8F\u53D1\u751F\u5185\u90E8\u9519\u8BEF