基于Struts2的通用文件上传实现

该文件上传实现可以限制上传文件的类型,限制上传文件的最大字节数,上传文件既可以存储在相对路径下,也可以存储在绝对路径下。

一、Model类源代码

Java代码
public class Attachments {
private long id;
private String name; //文件名
private String path; //上传文件存放的子目录路径
private Long fileSize; //文件大小,单位为K
private String contentType; //文件类型
private String refName = "attachment"; //引用名称,默认为attachment,可用于区分普通附件与特殊附件。
private String entityName; //指定与附件关联的表单的实体名称
private String entityId; //指定与附件关联的表单的主键值
private String creator; //创建人
private Timestamp createDate; //创建时间
private File attachFile; //待上传的文件对象
......
}

public class Attachments {
private long id;
private String name; //文件名
private String path; //上传文件存放的子目录路径
private Long fileSize; //文件大小,单位为K
private String contentType; //文件类型
private String refName = "attachment"; //引用名称,默认为attachment,可用于区分普通附件与特殊附件。
private String entityName; //指定与附件关联的表单的实体名称
private String entityId; //指定与附件关联的表单的主键值
private String creator; //创建人
private Timestamp createDate; //创建时间
private File attachFile; //待上传的文件对象
......
}

二、Action类源代码

Java代码
public class UploadAction extends BaseAction {
private UploadService uploadService;
private Attachments attach;

//限制
private String allowTypes = "";
private long maxSize = 0; //字节

//上传的文件
private File upload;
private String uploadFileName;
private String uploadContentType;

......

//获取与表单关联的所有附件信息
public String attachList() throws Exception{
List attachList = uploadService.queryAttachments(attach);
getValueStack().set("attachList", attachList);

return SUCCESS;
}

//上传附件
public String upload() throws Exception{
String method = getRequest().getMethod();
if(method.equalsIgnoreCase("post")){
if(upload != null){
if(upload.length() <= 0){
throw new RuntimeException("上传的文件不能为空!");
}
if(maxSize > 0 && upload.length() > maxSize){
throw new RuntimeException("上传的文件不能超过" + maxSize + "字节!");
}

allowTypes = CommonUtil.trim(allowTypes);
if(CommonUtil.isNotEmpty(allowTypes)){
int idx = uploadFileName.lastIndexOf(".");
String extendName = uploadFileName.substring(idx+1); //扩展名
List typesList = CommonUtil.toList(allowTypes, ",");
if(!typesList.contains(extendName)){
throw new RuntimeException("只能上传扩展名为[ " + allowTypes + " ]的文件!");
}
}

attach.setAttachFile(upload);
attach.setName(uploadFileName);
attach.setFileSize(new Long(upload.length() / 1024)); //K
attach.setContentType(uploadContentType);
attach.setCreator(SecurityUtil.getUserId());
attach.setCreateDate(DatetimeUtil.nowTimestamp());

uploadService.addAttachment(attach);

}else{
return INPUT;
}
}else{
return INPUT;
}

return SUCCESS;
}

//删除附件
public String attachDelete() throws Exception{
Map map = RequestUtil.getParameterMap(getRequest(), "chk_o_");
uploadService.deleteAttachment(map);

StringBuffer sb = new StringBuffer();
sb.append("attachList.action?attach.entityName=" + CommonUtil.trim(attach.getEntityName()));
sb.append("&attach.entityId=" + CommonUtil.trim(attach.getEntityId()));
sb.append("&attach.refName=" + CommonUtil.trim(attach.getRefName()));
sb.append("&attach.path=" + CommonUtil.trim(attach.getPath()));
sb.append("&allowTypes=" + CommonUtil.trim(allowTypes));
sb.append("&maxSize=" + maxSize);

getValueStack().set("url", sb.toString());

return SUCCESS;
}

//下载附件
public String download() throws Exception{
return SUCCESS;
}

public InputStream getTargetFile() throws Exception{
attach = uploadService.getAttachment(attach.getId());
uploadFileName = URLEncoder.encode(attach.getName(), "UTF-8"); //解决中文乱码问题

String filePath = attach.getPath();
if(filePath.indexOf(":") == -1){ //相对路径
return ServletActionContext.getServletContext().getResourceAsStream(filePath);
}else{ //绝对路径
return new FileInputStream(filePath);
}
}
}

public class UploadAction extends BaseAction {
private UploadService uploadService;
private Attachments attach;

//限制
private String allowTypes = "";
private long maxSize = 0; //字节

//上传的文件
private File upload;
private String uploadFileName;
private String uploadContentType;

......

//获取与表单关联的所有附件信息
public String attachList() throws Exception{
List attachList = uploadService.queryAttachments(attach);
getValueStack().set("attachList", attachList);

return SUCCESS;
}

//上传附件
public String upload() throws Exception{
String method = getRequest().getMethod();
if(method.equalsIgnoreCase("post")){
if(upload != null){
if(upload.length() <= 0){
throw new RuntimeException("上传的文件不能为空!");
}
if(maxSize > 0 && upload.length() > maxSize){
throw new RuntimeException("上传的文件不能超过" + maxSize + "字节!");
}

allowTypes = CommonUtil.trim(allowTypes);
if(CommonUtil.isNotEmpty(allowTypes)){
int idx = uploadFileName.lastIndexOf(".");
String extendName = uploadFileName.substring(idx+1); //扩展名
List typesList = CommonUtil.toList(allowTypes, ",");
if(!typesList.contains(extendName)){
throw new RuntimeException("只能上传扩展名为[ " + allowTypes + " ]的文件!");
}
}

attach.setAttachFile(upload);
attach.setName(uploadFileName);
attach.setFileSize(new Long(upload.length() / 1024)); //K
attach.setContentType(uploadContentType);
attach.setCreator(SecurityUtil.getUserId());
attach.setCreateDate(DatetimeUtil.nowTimestamp());

uploadService.addAttachment(attach);

}else{
return INPUT;
}
}else{
return INPUT;
}

return SUCCESS;
}

//删除附件
public String attachDelete() throws Exception{
Map map = RequestUtil.getParameterMap(getRequest(), "chk_o_");
uploadService.deleteAttachment(map);

StringBuffer sb = new StringBuffer();
sb.append("attachList.action?attach.entityName=" + CommonUtil.trim(attach.getEntityName()));
sb.append("&attach.entityId=" + CommonUtil.trim(attach.getEntityId()));
sb.append("&attach.refName=" + CommonUtil.trim(attach.getRefName()));
sb.append("&attach.path=" + CommonUtil.trim(attach.getPath()));
sb.append("&allowTypes=" + CommonUtil.trim(allowTypes));
sb.append("&maxSize=" + maxSize);

getValueStack().set("url", sb.toString());

return SUCCESS;
}

//下载附件
public String download() throws Exception{
return SUCCESS;
}

public InputStream getTargetFile() throws Exception{
attach = uploadService.getAttachment(attach.getId());
uploadFileName = URLEncoder.encode(attach.getName(), "UTF-8"); //解决中文乱码问题

String filePath = attach.getPath();
if(filePath.indexOf(":") == -1){ //相对路径
return ServletActionContext.getServletContext().getResourceAsStream(filePath);
}else{ //绝对路径
return new FileInputStream(filePath);
}
}
}

三、Service类源代码

Java代码
public class UploadService extends BaseService {
/**
* 保存附件信息并将附件文件存储到指定目录下
*/
public void addAttachment(Attachments attach)throws Exception{
if(CommonUtil.isEmpty(attach.getRefName())) attach.setRefName("attachment");

//文件存储基路径
String path = CommonUtil.trim(attach.getPath());
if(CommonUtil.isNotEmpty(path)){
if(path.endsWith("/") == false && path.endsWith("\\") == false){
path += File.separator;
}
if(path.startsWith("/")==false && path.startsWith("\\")==false){
if(Constants.attachBasePath.endsWith("/")==false && Constants.attachBasePath.endsWith("\\")==false){
path = File.separator + path;
}
}
}
path = Constants.attachBasePath + path;
attach.setPath(path);

save(attach);

//文件存储路径
if(path.endsWith("/") == false && path.endsWith("\\") == false){
path += File.separator;
}
path += attach.getId() + "_o_" + attach.getName();
attach.setPath(path);
update(attach);

//目标文件
String filePath = path;
if(filePath.indexOf(":") == -1) filePath = ServletActionContext.getRequest().getRealPath(filePath); //不是绝对路径就转成绝对路径

File dstFile = new File(filePath);
FileUtil.createPath(dstFile.getParent()); //目标目录不存在时创建

//文件保存
try{
FileUtil.copyFile(attach.getAttachFile(), dstFile);
}catch(FileNotFoundException ex){
throw new ServiceException("文件不存在:" + attach.getName());
}
}

/**
* 删除选中的附件信息及其对应的文件
*/
public void deleteAttachment(Map map) throws ServiceException{
List pathList = new ArrayList();

for(Iterator it=map.keySet().iterator();it.hasNext();){
String key = (String)it.next();
String value = (String)map.get(key);

Attachments attach = (Attachments)load(Attachments.class, new Long(value));
if(attach != null){
pathList.add(attach.getPath());
delete(attach);
}
}

for(int i=0;i<pathList.size();i++){
String filePath = (String)pathList.get(i);
if(filePath.indexOf(":") == -1){
filePath = ServletActionContext.getRequest().getRealPath(filePath);
}
File file = new File(filePath);
FileUtil.deleteFile(file);
}
}

/**
* 查找附件
*/
public List queryAttachments(Attachments attach)throws Exception{
DetachedCriteria dc = DetachedCriteria.forClass(Attachments.class);
CriteriaUtil.eq(dc, "entityName", attach.getEntityName());
CriteriaUtil.eq(dc, "entityId", attach.getEntityId());
CriteriaUtil.eq(dc, "refName", attach.getRefName());

dc.addOrder(Order.asc("createDate"));

return findByCriteria(dc);
}

public Attachments getAttachment(long id)throws Exception{
return (Attachments)load(Attachments.class, new Long(id));
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值