首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Struts2文件上传

Struts2文件上传

作者头像
HUC思梦
发布2020-09-03 10:47:47
5730
发布2020-09-03 10:47:47
举报

=======================上传(过滤大小及类型)下载文件(弹出框以流的方式下载)=======================

1)上传jsp:

<form enctype="multipart/form-data" action="fileUpLoadAction.action" method="post">
<h3 align="center">
Struts2文件上传示例
</h3>
用户名:
<input type="text" name="uname" />
<br />
年龄:
<input type="text" name="age" />
<br />
照片:&nbsp;&nbsp;&nbsp;
<input type="file" value="选择图片" name="image2" />
<input type="submit" value="上传" />
</form>

注:1) enctype="multipart/form-data" 表单中如果要上传附件那么这里要加这个属性,作用是表单是的数据以二进制形式提交 2) method="post" 有附件上传那么提交方式必然是post方式 2) 上传Action:

/*
* 必须继承ActionSupport类,则否fileUpload拦截器无效
*/
public class FileUpLoadAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private File image2; // 变量名必须与jsp页面中的file控件的name相同
private String image2FileName; // 必须--File变量的名字+ "FileName"
private List<String> listNames;

public File getImage2() {
return image2;
}

public void setImage2(File image2) {
this.image2 = image2;
}

public String getImage2FileName() {
return image2FileName;
}

public void setImage2FileName(String image2FileName) {
this.image2FileName = image2FileName;
}

public List<String> getListNames() {
return listNames;
}

public void setListNames(List<String> listNames) {
this.listNames = listNames;
}

public String execute() throws Exception {

// 放图片的路径:E:\apache-tomcat-6.0.18\webapps\StrutsFileUpDown\images

String realpath = ServletActionContext.getServletContext().getRealPath("/images");

//不存在则创建,代码没写

if (image2 != null) {
// 放图片的路径+图片的名称
File savefile = new File(realpath + "/" + image2FileName);

// FileUtils.copyFile(file1,file2);file1,file2都是文件类型File;把file1拷贝到file2
FileUtils.copyFile(image2, savefile);
}

// 接收用户名和年龄
String userName = ServletActionContext.getRequest().getParameter("uname");
String age = ServletActionContext.getRequest().getParameter("age");

/**
* 读取文件名列表
*/
//读取图片的名称返回一个list列表
listNames = findFileNames(realpath );
return "success";
}

/**
* 读取文件名的列表
* 
* @param path
* 放图片的路径
* @return 把路径中的图片名取出来存在List里
*/
private List<String> findFileNames(String path) {
List<String> listNames = new ArrayList<String>();

File file = new File(path);
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile()) {
// 得到图片的名称 123.jpg
String fileName = f.getName();
listNames.add(fileName);
}
}

return listNames;
}
}

3)下载Action

public class DownloadAction {

private String fileName; 

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public InputStream getInputStream() {
System.out.println("getFileName()="+getFileName());
InputStream ins = ServletActionContext.getServletContext().getResourceAsStream("/images/" + fileName);
return ins;
//查找具有给定名称的资源。返回 inputstream
//相当于取得File文件后,再new InputStream(file)一样的结果
//以'/'开头时默认是从此类所在的包下取资源,以'/'开头则是从ClassPath(Src根目录)根下获取。
//E:\apache-tomcat-6.0.18\webapps\StrutsFileUpDown\images 其实E:\apache-tomcat-6.0.18\webapps \StrutsFileUpDown\就是根
}

public String execute(){
return "success";
//下载不用写返回页面
}


}

注:execute()必须走,走 execute(),在走getInputStream --------->把附件以流的方式写入浏览器中,以弹出框的形式下 载

4)struts.xml

<?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.i18n.encoding" value="UTF-8" />    

<package name="filePackage" extends="struts-default">

<action name="fileUpLoadAction" class="com.cs.fileupload.action.FileUpLoadAction">
<result name="success">index.jsp</result>
<result name="input">error.jsp</result>
<!-- input意思是当上传的文件大小和类型不符合要求时就会返回一个input,这个input在ActionSupport
类中所以上传类必须继承ActionSupport -->

<!-- 文件上传拦截器,struts自已写好的,我们调用就可以了 -->
<interceptor-ref name="fileUpload"> 
<!-- 上传文件的文件类型要求是哪几个类型,并且以,号分隔 --> 
<param name="allowedTypes">image/bmp,image/png,image/gif</param> 
<!-- 上传文件的文件的大小允许是多少字节 --> 
<param name="maximumSize">102400</param> 
</interceptor-ref> 
<interceptor-ref name="defaultStack" /> 
</action>
<action name="downloadAction" class="com.cs.fileupload.action.DownloadAction">
<!-- 可以实现文件的下载功能 -->
<result type="stream">
<!-- 让浏览器总是提示一个文件下载对话框 -->
<param name="contentType">application/octet-stream</param>
<!-- 返回的InputStream对象将被发送到浏览器 -->
<param name="inputName">inputStream</param>
<!-- 文件处理方式 ${}内部为ognl表达式-->
<param name="contentDisposition">attachment;fileName=${fileName}</param>
<!-- 通过OutputStream对象向浏览器发送数据时使用的缓冲区的长度,为了是提高文件的下载速度 -->
<param name="bufferSize">4096</param>
</result>
</action>

</package>

</struts>

5)错误页面 error.jsp

<%@ taglib uri="/struts-tags" prefix="s"%>
<body>
<!-- 上传如果发错会进入这个页面,并用这个标签显出错误信息,并且以英文的方式显示出来-->
<h3><s:fielderror/></h3>
<h4><a href="fileUpLoadAction.action">返回图片上传页</a></h4>
</body>

出错信息在: 传输文件时的信息解释:(struts核心包下/org.apache.struts2/struts-messages.properties文件里)

struts.messages.error.content.type.not.allowed=不支持上传该类型的文件 struts.messages.error.file.too.large=上传图片失败:图片太大 struts.messages.error.uploading=上传文件时发生错误

===========================页面用struts标签========================================== 1)如果页面用struts标签。 2)web.xml中配置时用的是 <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> 那么访问JSP时就报错,找不到struts标签,因为配置时用的是*.action,只有.action形式才走struts框架,那么这时我们就可以把配置改下加 <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>

这样我们就可以在访问jsp时,让它走struts框架。

web.xml完整代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern> 
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>    
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

3)还有另外一种方法是把*.action改成/*

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-07-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档