文件上传的原理:
表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:
1)
application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式。
2)
multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数里。
3)
text/plain:这种方式主要适用于直接通过表单发送邮件的方式。
文件上传是web应用经常用到的一个知识。原理是,通过为表单元素设置enctype=”multipart/form-data”属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。
在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件(http://commons.apache.org/fileupload/),另一个是Oreilly组织的COS框架(http://www.servlets.com/cos/)。利用这两个框架都能很方便的实现文件的上传。
以下是实现的全部代码,仅供参考:
JAR需求:除了Struts2的基本jar必须之外加入commons-fileupload.jar和commons-io.jar即可!
一、upload.jsp:
<%@ page language="java" contentType="text/html; charset=GB2312"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>多文件上传</title>
</head>
<body>
<font color="red"><s:fielderror /> </font>
<form action="upload.action" method="POST"
enctype="multipart/form-data">
<!-- 设置二个文件域,名字相同 -->
选择第一个文件:
<input type="file" name="upload" size="50" />
<br />
选择第二个文件:
<input type="file" name="upload" size="50" />
<input type="submit" value=" 上传 " />
</form>
</body>
</html>
二、struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml" />
<package name="struts-upload" extends="struts-default">
<action name="upload" class="uploadAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/bmp,image/png,image/gif,image/jpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" ></interceptor-ref>
<result name="success">/manage/success.jsp</result>
<result name="input">upload.jsp</result>
</action>
</package>
</struts>
三、UploadAction.java:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts2.ServletActionContext;
/**
* 处理多文件上传的Action类
*
* @authorqiujy
* @version1.0
*/
public class UploadAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int BUFFER_SIZE = 16 * 10240;
private String dstPath = null;
private InputStream in = null;
private OutputStream out = null;
/**
* 用File数组来封装多个上传文件域对象
*/
private File[] upload;
/**
* 用String数组来封装多个上传文件名
*/
private String[] uploadFileName;
/**
* 用String数组来封装多个上传文件类型
*/
private String[] uploadContentType;
/**
* 保存上传的文件(spring注入)
*/
private String saveFilesDir;
/**
* 保存上传的图片(srping注入)
*/
private String saveImageDir;
public void setUpload(File[] upload) {
this.upload = upload;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setSaveFilesDir(String saveFilesDir) {
this.saveFilesDir = saveFilesDir;
}
public void setSaveImageDir(String saveImageDir) {
this.saveImageDir = saveImageDir;
}
// 自己封装的一个把源文件对象复制成目标文件对象
private void copy(File src, File dst) throws Exception {
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
}
public String execute() throws Exception {
// 处理每个要上传的文件
for (int i = 0; i < upload.length; i++) {
if (uploadFileName[i].length() != 0) {
// 根据服务器的文件保存地址和原文件名创建目录文件全路径
if (uploadContentType[i].startsWith("image")) {
dstPath = ServletActionContext.getServletContext()
.getRealPath(saveImageDir + uploadFileName[i]);
} else {
dstPath = ServletActionContext.getServletContext()
.getRealPath(saveFilesDir + uploadFileName[i]);
}
if (upload[i] != null)
copy(upload[i], new File(dstPath));
}
}
return SUCCESS;
}
}
注意:页面中上传标签<s:file name="xxx" />对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。
四、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">
<!-- 配置struts2 -->
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 加载spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-configs/config-*.xml</param-value>
</context-param>
<!-- 配置spring监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
注意:两个filter-mapping的顺序不要颠倒了!
五、在struts.properties中设置上传参数:
##### temporary directory #####
struts.multipart.saveDir=C\:/temp
##### default(CommonsFileUpload) #####
#struts.multipart.parser=
##### default(2M) #####
struts.multipart.maxSize= 10485760
六、在message_zh_CN.properties中设置错误消息:
struts.messages.error.uploading=上传文件失败!
struts.messages.error.file.too.large=上传文件太大!
struts.messages.error.content.type.not.allowed=赞不支持该格式上传!
注意:该错误消息必须写在国际化中才有效!
分享到:
相关推荐
网上的Struts2进行的文件下载一般都是单文件或者固定的文件,并没有(很少)实现随意文件的下载的例子 提供多文件上传,上传成功后,提供刚上传的文件下载功能(其他的都可以在其上面进行扩充) 多文件 上传 下载...
用Struts框架实现单文件上传功能(初学者的入门项目案例),本项目适合课后作业的哦.
网上有些这样的例子,但是下了几个都没有跑起来,哎,希望那些发文章的人要发就发全的,别发个半生不熟的。... 现在自己整理了一个Struts2+ExtJS2实现文异步文件上传,没法上传图片无法看到效果,直接上源码吧。
Struts2 文件上传下载 多文件 单文件 实例;支持单个或多个文件的上传下载,并且自定义上传文件的大小和类型!!!
文件上传struts2实现实例 文件上传 单文件和多文件上传
Struts 2是通过Commons FileUpload文件上传。Commons FileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的...
这是根据uploadify3 2结合struts2搭建的文件上传环境 可以直接导入eclipse运行 每步实现基本都加了注释 以下是我碰到的问题: 1 判断session是否失效 本实例没测试这个问题 但在工作项目中碰到了 但原因在这里...
struts2 +jquey uploadify3 2 实现多文件上传 可以运行的myeclipse工程 绝对好用 访问方式http: 127 0 0 1:8080 Struts2Uploadify upload jsp uploadify 使用说明: <a href "javascript:$ "#file ...
struts2中的文件上传和下载示例 struts2中的文件上传和下载示例 struts2中的文件上传和下载示例
这是本人实现的struts任意多文件上传的小实例,请多多指教。
这是一个struts2实现的文件上传和下载例子,支持多文件上传,并且显示单文件上传的进度条。
MultiFileUpload Struts2多文件 Struts2多文件上传 Struts2上传 Struts2文件上传,随手写的一个Demo实例
struts2文件上传实例,程序员宝典......
用struts2.0实现的文件上传,用myeclipse6.6直接导入便可运行。
Struts2.0实现文件上传例子
这是一个完整的上传例子,用的mysql数据库,数据库中存储上传的路径,数据库中只有一个id(主键),和一个其他字段,
这是一个struts2实例 涉及的技术包括: 1.自定义过滤器 2.文件上传下载 3.登录功能 等等
自己写的用struts2实现上传的例子 带页面的 直接运行 访问index.jsp就可以
struts2文件上传例子(支持大文件)
struts2多文件上传例子及单文件上传例子