一、导入包

  • 需要将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. 编译安装GCC 4.7.2

    from:http://blog.chinaunix.net/uid-20717979-id-3485672.html 安装gcc需要GMP.MPFR.MPC这三个库,可从ftp://gcc.gnu. ...

  2. unix/linux中图形界面那些事

    我们知道unix/linux刚开始的时候是没有图形界面的,随着时代的发展,排版.制图.多媒体应用越来越普遍了,这些需求都需要用到图形界面(Graphical User Interface).为此,MI ...

  3. 文本框不够长,显示“XXX...”

    WPF: How to make the TextBox/TextBlock/Label show "xxx..." if the text content too long? 设 ...

  4. Scene视图辅助线绘制

    有时候需要在Scene视图中绘制一些辅助线,方便进行一些编辑的工作,可以通过如下类和函数完成: 绘制辅助线,相关类: Gizmos类:用于在Scene视图中绘制调试信息或辅助线,这些辅助线只有在Sce ...

  5. Nodejs建站笔记-注册登录流程的简单实现

    1. 使用Backbone实现前端hash路由 登录注册页面如下: 初步设想将注册和登录作为两个不同的url实现,但登录和注册功能的差距只有form表单部分,用两个url实现显然开销过大,所以最终方案 ...

  6. Slip.js – 在触摸屏上实现列表的滑动排序功能

    Slip.js 是一个很小的 JavaScript 库,用于实现对触摸屏的互动 Swipe 和对元素重新排序列表(Reordering).Slip.js 没有任何的依赖,你可以通过自定义 DOM 事件 ...

  7. 求1+2+3+...+n

    求1+2+3+...+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C). 卧槽,剑指Offer竟然有这样的题... public ...

  8. 解决安装office2013时提示已安装相同版本的office

    例如出现如上所示的图: ------------------------------------------------------------------ 在尝试使用官方的卸载清理工具无果后, 终极 ...

  9. mysql线上一些隐患查询sql

    开发写了几个语句,觉得查询结果跟逻辑有点不相符,就拿到这里一起分析了下. 语句如下: select tp.title, tp.amount, ifnull( ) as aInvestAmount, i ...

  10. 检测局域网中还可用的ip地址

    #!/bin/bash ` do { .$i &>/dev/null ];then echo "192.168.1.$i is not used" fi } done