Struts2(十五)实现文件上传
一、导入包
- 需要将commons-fileupload和commons-io包和struts包一起导入
实现步骤:
- 在Jsp页面实现客户端选择上传文件
- 配置Struts.xml,拦截器会自动接收上传的文件
- 在Action中实现代码上传文件存入服务器中
- 跳转至新页面展示上传的文件
二、单个文件上传
上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>单个文件上传</title>
</head>
<body>
<form action="doUpload.action" method="post" enctype="multipart/form-data">
<input type="file" name="upload"/>
<input type="submit" value="上传">
</form>
</body>
</html>
上传成功页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传成功</title>
</head>
<body>
<h1>上传的文件</h1>
<img alt="图片" src="<s:property value='savePath'/>" /> </body>
</html>
UploadAction
package com.pb.web.action; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport { //上传文件全路径、类型、文件名
private File upload;
private String uploadContentType;
private String uploadFileName;
//新文件保存路径和名称
private String savePah; public String doUpload() throws IOException{
System.out.println(upload);
System.out.println(uploadContentType);
System.out.println(uploadFileName);
String newFileName=System.currentTimeMillis()+uploadFileName.substring(uploadFileName.lastIndexOf("."));
System.out.println("新的文件名:"+newFileName);
//获取上传路径
savePah=ServletActionContext.getServletContext().getRealPath("/upload/"+newFileName);
System.out.println("上传保存的路径和名称:"+savePah);
//使用文件输入、输出流写入文件
FileInputStream fis=new FileInputStream(upload);
FileOutputStream fos=new FileOutputStream(savePah);
//设置缓冲区大小
/*byte[] bytes=new byte[1024];
//读取文件
int length=fis.read(bytes);
while(length>0){
//写入文件
fos.write(bytes);
length=fis.read(bytes);
}*/
//复制文件
IOUtils.copy(fis, fos);
fos.flush();
fos.close();
fis.close(); return SUCCESS;
} public File getUpload() {
return upload;
} public void setUpload(File upload) {
this.upload = upload;
} public String getUploadContentType() {
return uploadContentType;
} public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
} public String getUploadFileName() {
return uploadFileName;
} public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
} public String getSavePah() {
return savePah;
} public void setSavePah(String savePah) {
this.savePah = savePah;
} }
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="doUpload" class="com.pb.web.action.UploadAction" method="doUpload">
<result name="success">
/singleUploadSuccess.jsp
</result>
<result name="error">
/error.jsp
</result>
<result name="input">
/singleUpload.jsp
</result>
</action>
</package>
</struts>
三、限制文件大小
- 在struts.xml中配置常量
<constant name="struts.multipart.maxSize" value="5000000"/>
5M大小
在action下配置拦截器
<interceptor-ref name="fileUpload">
<param name="maximumSize">5000000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>

五、限制文件类型
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/pjpeg,image/jpeg,image/gif,image/png</param>
<param name="maximumSize">5000000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.multipart.maxSize" value="1000000" />
<constant name="struts.multipart.saveDir" value="/tmp"/>
<package name="default" namespace="/" extends="struts-default">
<action name="doupload" class="com.pb.web.action.UploadAction" method="upload">
<interceptor-ref name="fileUpload">
<param name="maximumSize">40000</param>
<param name="allowedTypes">image/jpeg,image/pjpeg,image/gif,image/png</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">
/oneUploadSuccess.jsp
</result>
<result name="input">
/error.jsp
</result>
</action>
</package>
</struts>
六、多个文件上传
和单个文件上传一个只是接收参数变为数组
mulUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>多个 文件上传</title>
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
function addFile(){
/* 获取父元素*/
var parent=$("#add").parent();
/*创建新的节点 */
var file=$("<input type='file' name='upload' /><br/>");
/* 添中节点 */
parent.append(file); }
</script>
</head>
<body>
<form action="doupload.action" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />
<input type="button" value="继续添加" onclick="addFile();" id="add"/>
<input type="submit" value="上传" /><br/>
</form>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传失败</title>
</head>
<body>
上传失败<a href="mulUpload.jsp">返回</a>
<s:debug/>
</body>
</html>
mulUploadSuccess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传成功</title>
</head>
<body>
<!--显示上传的图片 -->
<s:iterator value="savePath" var="i">
<img alt="图片" src="<s:property value='#i'/>">
</s:iterator>
<s:debug/>
</body>
</html>
UploadAction.java
package com.pb.web.action; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport {
// 文件上传路径、类型、名称
private List<File> upload;
private List<String> uploadFileName;
private List<String> uploadContentType;
// 新的文件名称
private List<String> savePath=new ArrayList<String>(); public String upload() throws IOException {
for (int i = 0; i < upload.size(); i++) {
//重命名 用长时间+原来的文件名
String newFileName = System.currentTimeMillis()+""+uploadFileName.get(i);
System.out.println("新的文件名:"+newFileName);
//获取上传路径
//将新的路径和名称添加入集合
savePath.add(ServletActionContext.getServletContext().getRealPath("/upload/"+newFileName));
System.out.println(savePath.get(i));
//读取文件
FileInputStream fis=new FileInputStream(upload.get(i));
//写入文件
FileOutputStream fos=new FileOutputStream(savePath.get(i));
//将文件从输入流,复制到输出流中
IOUtils.copy(fis, fos);
//强制刷新输出流,清空缓冲区
fos.flush();
fos.close();
fis.close();
} return SUCCESS;
} public List<File> getUpload() {
return upload;
} public void setUpload(List<File> upload) {
this.upload = upload;
} public List<String> getUploadFileName() {
return uploadFileName;
} public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
} public List<String> getUploadContentType() {
return uploadContentType;
} public void setUploadContentType(List<String> uploadContentType) {
this.uploadContentType = uploadContentType;
} public List<String> getSavePath() {
return savePath;
} public void setSavePath(List<String> savePath) {
this.savePath = savePath;
} }
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<!--设置文件大小拦截器 -->
<constant name="struts.multipart.maxSize" value="10000000"></constant> <constant name="struts.multipart.saveDir" value="/tmp"/>
<package name="default" namespace="/" extends="struts-default">
<action name="doupload" class="com.pb.web.action.UploadAction" method="upload"> <interceptor-ref name="fileUpload">
<!--设置文件类型拦截器 -->
<param name="allowedTypes">image/jpeg,image/pjpeg,image/png</param>
<!--设置文件大小拦截器 -->
<param name="maximumSize">5000000</param>
</interceptor-ref>
<!-- struts默认的拦截器 -->
<interceptor-ref name="defaultStack" /> <result name="success">
/mulUploadSuccess.jsp
</result>
<result name="input">
/error.jsp
</result>
</action>
</package>
</struts>
更详细的请参考:struts下载包中的帮助文档:
file://stuts2/struts2-2.3.4.1-all/struts-2.3.4.1/docs/WW/file-upload.html
Struts2(十五)实现文件上传的更多相关文章
- 渗透测试学习 十五、 文件上传&&解析漏洞
大纲:文件解析漏洞 上传本地验证绕过 上传服务器验证绕过 文件解析漏洞 解析漏洞主要说的是一些特殊文件被IIS.Apache.Nginx在某些情况下解释成脚本文件格式的漏洞. IIS 5.x/6.0解 ...
- Struts(二十六):文件上传
表单的准备 想要使用html表单上传一个或多个文件 1.须把html表单的enctype属性设置为multipart/form-data 2.须把html表单的method属性设置为post 3.须添 ...
- Struts2框架下的文件上传文件类型、名称约定
Struts2框架下的文件上传机制:1.通过multipart/form-data form提交文件到服务器2.文件名是通过什么地方设置的?在strust2的FileUploadInterceptor ...
- struts2解决动态多文件上传的问题(上传文件与数据库字段一一对应)(转)
struts2多文件上传我想只要会用struts2的朋友都不会陌生,但是怎么在action中根据用户上传的文 件把文件路径写到数据库中对应的字段上呢?ps:我的意思是这样,页面上有固定的5个上传文件的 ...
- Struts2学习笔记(十一)——文件上传
1.单文件上传 单文件上传步骤: 1)创建上传jsp页面 文件上传的表单提交方式必须是POST方式,编码类型:enctype="multipart/form-data",默认是 a ...
- Spring MVC 使用介绍(十四)文件上传下载
一.概述 文件上传时,http请求头Content-Type须为multipart/form-data,有两种实现方式: 1.基于FormData对象,该方式简单灵活 2.基于<form> ...
- Struts2 使用Jquery+ajax 文件上传
话不多说 直接上代码 前台js: var formData = new FormData(); formData.append("file1",$("#file1&quo ...
- Struts2的简单的文件上传
1文件上传的流程: 第一步:首先得用表单标签的<s:file>在客户端接收上传的文件例如: <%@ page language="java" import=&qu ...
- 深入分析JavaWeb Item47 -- Struts2拦截器与文件上传下载
一.struts2中的拦截器(框架功能核心) 1.过滤器VS拦截器 过滤器VS拦截器功能是一回事. 过滤器是Servlet规范中的技术,能够对请求和响应进行过滤. 拦截器是Struts2框架中的技术. ...
随机推荐
- android 隐藏标题栏的方法
1:单个activity里 onCreate() { super.onCreate(); requestWindowFeature(Window.FEATURE_NO_TITLE); setConte ...
- C# 事件和委托
相信大家在面试的时候会经常问到事件和委托的区别,为什么.net中需要事件和委托这样类似的问题吧,对于一些初学者来说可平时用的过程中也不知道为什么, 只知道这样用,而对于其中的实现机制不是很清楚, 所以 ...
- STL中vector小结
()使用vector之前必须包含头文件<vector>:#include<vector> ()namespace std{ template <class T, clas ...
- Java 集合系列15之 Set架构
前面,我们已经系统的对List和Map进行了学习.接下来,我们开始可以学习Set.相信经过Map的了解之后,学习Set会容易很多.毕竟,Set的实现类都是基于Map来实现的(HashSet是通过Has ...
- 15款提高工作效率的 Web 项目管理工具
在今天的快节奏的商业世界里,能够通过计划.组织.和管理资源池以及评估开发资源的模式来管理一个项目,是一个很艰巨的任务. 有很多现成的项目管理软件来帮助减轻项目管理的负担,并且他们几乎覆盖了所有类型的业 ...
- 一起Polyfill系列:让Date识别ISO 8601日期时间格式
一.什么是ISO 8601日期时间格式 ISO 8601是国际标准化组织制定的日期时间表示规范,全称是<数据存储和交换形式·信息交换·日期和时间的表示方法>. 示例: 1. 2014-12 ...
- AC自动机 - 多模式串的匹配 --- HDU 3695 Computer Virus on Planet Pandora
Problem's Link Mean: 有n个模式串和一篇文章,统计有多少模式串在文章中出现(正反统计两次). analyse: 好久没写AC自动机了,回顾一下AC自动机的知识. 本题在构造文章的时 ...
- 微信公众平台入门开发教程.Net(C#)框架
一.序言 一直在想第一次写博客,应该写点什么好?正好最近在研究微信公众平台开发,索性就记录下,分享下自己的心得,也分享下本人简单模仿asp.net运行机制所写的通用的微信公众平台开发.Net(c#)框 ...
- VB 2015 的 闭包(Closure)
是的,你没看错,这篇文章讲的不是 ECMAScript . 目前 VB 14 比 C# 6 领先的功能里面,有个即将在 C# 7 实现的功能,叫做"本地方法".这个功能与" ...
- 重新想象 Windows 8 Store Apps (59) - 锁屏
[源码下载] 重新想象 Windows 8 Store Apps (59) - 锁屏 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 锁屏 登录锁屏,获取当前程序的锁 ...