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框架中的技术. ...
随机推荐
- 使用ECMAscript5中的forEach函数遍历数组
1 var a = [1,2,3]; 2 a.forEach(function(value,index,arr){ 3 arr[index] = value + index; 4 }) 5 conso ...
- ruby -- 基础学习(三)设置中国时区时间
Rails连接MYSQL数据库,默认显示UTC时间.如果想要改成中国时区时间,按照下面修改: 在config/application.rb中找到 class Application < Rail ...
- AVL树(二)之 C++的实现
概要 上一章通过C语言实现了AVL树,本章将介绍AVL树的C++版本,算法与C语言版本的一样. 目录 1. AVL树的介绍2. AVL树的C++实现3. AVL树的C++测试程序 转载请注明出处:ht ...
- [Python] Create a Django project in Pycharm
From: http://blog.csdn.net/u013088062/article/details/50158239 From: http://blog.csdn.net/u013088062 ...
- iOS-多线程-GCD
一. 名词解释: 1. 进程和线程 进程是指在系统中正在运行的一个应用程序.每个进程之间都是独立的,每个进程均运行在期专用而且受到保护的内存空间中. 线程是指一个进程想要执行任务,就必须要有线程.线程 ...
- js-弹出窗口
一.JS最常用三种弹出对话框 1.对话框 //弹出对话框并输出一段提示信息 function ale() { //弹出一个对话框 alert("提示信息!"); } 2.询问框 / ...
- IIS Express魔法堂:解除localhost域名的锁定
一.前言 单点登录是通过域名从cookie中获取登录信息,然后再根据cookie的键值对获取用户信息.但由于通过IIS Express调试应用时默认使用localhost作为域名且无法直接修改,导 ...
- Windows魔法堂:解决“由于启动计算机时出现页面文件配置问题.......”
一.前言 昨晚终于在VirtualBox中安装好Win7了,但在系统启动后弹出窗报“由于启动计算机时出现页面文件配置问题.......”,于是度娘一下.以下记录以供日后查阅. 二.原因 网上说的是在使 ...
- Vim杂记:Sublime的配色方案
一.前言 爱美之心人皆有之,sublime的配色实在好看,于是希望Vim也能这样. 二.配置 1.下载monokai(https://github.com/sickill/vim-monokai),然 ...
- IOS开发UI基础 UIAlertView的属性
UIAlertView1.Title获取或设置UIAlertView上的标题. 2.Message获取或设置UIAlertView上的消息 UIAlertView *alertView = [[UIA ...