一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Struts2实现文件上传功能实例解析

时间:2022-06-29 02:34:47 编辑:袖梨 来源:一聚教程网

一、 搭建struts2环境

在myeclipse下,右击项目->MyEclipse->Project Facets->install Apache Struts2。

如要自己搭建,需下载struts2包,写struts.xml配置文件。

web.xml文件配置如下:

struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
*.action

二、 文件上传

1.前台页面:

上传页面:


${result}

input name属性与后台命名一致。

上传失败页面:

上传失败

需:

2.后台Action

主要属性upload,uploadContentType,uploadFileName。

packagecom.yf.action;
importjava.io.File;
importorg.apache.commons.io.FileUtils;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionSupport;
publicclassUploadActionextendsActionSupport{
privateFile upload;
privateString uploadContentType;
privateString uploadFileName;
privateString result;
publicFile getUoload() {
returnupload;
}
publicvoidsetUpload(File upload) {
this.upload = upload;
}
publicString getUploadContentType() {
returnuploadContentType;
}
publicvoidsetUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
publicString getUploadFileName() {
returnuploadFileName;
}
publicvoidsetUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
publicString getResult() {
returnresult;
}
publicvoidsetResult(String result) {
this.result = result;
}
@Override
publicString execute()throwsException {
String path = ServletActionContext.getServletContext().getRealPath("/images");
File file =newFile(path);
if(!file.exists()){
file.mkdir();
}
System.out.println(upload);
FileUtils.copyFile(upload,newFile(file,uploadFileName));
result ="上传成功";
returnSUCCESS;
}
}

3.struts.xml文件配置

配置action及配置拦截器限制上传文件的类型及大小。

/index.jsp
/error.jsp
image/bmp,image/x-png,image/gif,image/jpeg
2M

4.新建properties文件

文件上传失败信息显示到前台,处理显示出错信息。

这里写图片描述

文件内容如下:

struts.messages.error.file.too/large=u4E0Au4F20u6587u4EF6u592Au5927u4E86uFF01
struts.messages.error.content.type.not.allowed=u4E0Au4F20u6587u4EF6u7C7Bu578Bu4E0Du7B26uFF01

即添加:

Name:struts.messages.error.file.too/large

value : 上传文件太大了!

Name : struts.messages.error.content.type.not.allowed

value: 上传文件类型不符!

运行结果如下:

选择jpg图片,大小不超过2M,运行后

这里写图片描述

选择非图片文件:

这里写图片描述

如需批量上传文件,将后台upload,uploadContentType,uploadFileName均改为List,循环读取上传文件保存到硬盘,前台加入input ,name属性一致。

热门栏目