一、导入包

  • 需要将commons-fileupload和commons-io包和struts包一起导入

实现步骤:

  1. 在Jsp页面实现客户端选择上传文件
  2. 配置Struts.xml,拦截器会自动接收上传的文件
  3. 在Action中实现代码上传文件存入服务器中
  4. 跳转至新页面展示上传的文件

二、单个文件上传

上传页面

<%@ 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(十五)实现文件上传的更多相关文章

  1. 渗透测试学习 十五、 文件上传&&解析漏洞

    大纲:文件解析漏洞 上传本地验证绕过 上传服务器验证绕过 文件解析漏洞 解析漏洞主要说的是一些特殊文件被IIS.Apache.Nginx在某些情况下解释成脚本文件格式的漏洞. IIS 5.x/6.0解 ...

  2. Struts(二十六):文件上传

    表单的准备 想要使用html表单上传一个或多个文件 1.须把html表单的enctype属性设置为multipart/form-data 2.须把html表单的method属性设置为post 3.须添 ...

  3. Struts2框架下的文件上传文件类型、名称约定

    Struts2框架下的文件上传机制:1.通过multipart/form-data form提交文件到服务器2.文件名是通过什么地方设置的?在strust2的FileUploadInterceptor ...

  4. struts2解决动态多文件上传的问题(上传文件与数据库字段一一对应)(转)

    struts2多文件上传我想只要会用struts2的朋友都不会陌生,但是怎么在action中根据用户上传的文 件把文件路径写到数据库中对应的字段上呢?ps:我的意思是这样,页面上有固定的5个上传文件的 ...

  5. Struts2学习笔记(十一)——文件上传

    1.单文件上传 单文件上传步骤: 1)创建上传jsp页面 文件上传的表单提交方式必须是POST方式,编码类型:enctype="multipart/form-data",默认是 a ...

  6. Spring MVC 使用介绍(十四)文件上传下载

    一.概述 文件上传时,http请求头Content-Type须为multipart/form-data,有两种实现方式: 1.基于FormData对象,该方式简单灵活 2.基于<form> ...

  7. Struts2 使用Jquery+ajax 文件上传

    话不多说 直接上代码 前台js: var formData = new FormData(); formData.append("file1",$("#file1&quo ...

  8. Struts2的简单的文件上传

    1文件上传的流程: 第一步:首先得用表单标签的<s:file>在客户端接收上传的文件例如: <%@ page language="java" import=&qu ...

  9. 深入分析JavaWeb Item47 -- Struts2拦截器与文件上传下载

    一.struts2中的拦截器(框架功能核心) 1.过滤器VS拦截器 过滤器VS拦截器功能是一回事. 过滤器是Servlet规范中的技术,能够对请求和响应进行过滤. 拦截器是Struts2框架中的技术. ...

随机推荐

  1. Machine Learning : Pre-processing features

    from:http://analyticsbot.ml/2016/10/machine-learning-pre-processing-features/ Machine Learning : Pre ...

  2. get新技能: 如何设置元素高度与宽度成特定比例。宽度改变,高度自动按比例改变。 例如设置宽高比16:9。

    设置宽高比在很多时候是有用的. 下面的栗子,我们设置一个容器的宽高比为16:9 //HTML代码片段 <div class="container"> <div c ...

  3. ECMASCRIPT 6中字符串的新特性

    本文将覆盖在ECMAScript 6 (ES6)中,字符串的新特性. Unicode 码位(code point)转义 Unicode字符码位的长度是21位[2].而JavaScript的字符串,是1 ...

  4. Exchange Server简介与搭建

    一.Exchange Server简介Exchange Server 是微软公司的一套电子邮件服务组件,是个消息与协作系统. 简单而言,Exchange server可以被用来构架应用于企业.学校的邮 ...

  5. django 快速实现登录

    前言 对于web开来说,用户登陆.注册.文件上传等是最基础的功能,针对不同的web框架,相关的文章非常多,但搜索之后发现大多都不具有完整性,对于想学习web开发的新手来说不具有很强的操作性:对于web ...

  6. PEP8 Python 编码规范

    一 代码编排1 缩进.4个空格的缩进(编辑器都可以完成此功能),不使用Tap,更不能混合使用Tap和空格.2 每行最大长度79,换行可以使用反斜杠,最好使用圆括号.换行点要在操作符的后边敲回车.3 类 ...

  7. Angular系列----AngularJS入门教程00:引导程序(转载)

    我们现在开始准备编写AngularJS应用——phonecat.这一步骤(步骤0),您将会熟悉重要的源代码文件,学习启动包含AngularJS种子项目的开发环境,并在浏览器端运行应用. 进入angul ...

  8. Sprint第三个冲刺(第四天)

    一.Sprint介绍 任务进度: 二.Sprint周期 看板: 燃尽图:

  9. HTML5使用ApplicationCache

    在html5中使用application cache可以把一些静态资源保存在客户端的浏览器上面.这样可以提高访问的速度,甚至是离线应用.关于application cache的优缺点:1.离线浏览 - ...

  10. 学习笔记(一)——MVC扩展

    1.视图引擎的作用,总结为两点: 查找视图 渲染视图 ViewEngine即视图引擎, 在ASP.NET MVC中将ViewEngine的作用抽象成了 IViewEngine 接口. 默认情况下,AS ...