struts2,action上传文件
通过servlet实现文件上传,可以用用servlet接受到request的值的话:主要是这句话
List<?> items = upload.parseRequest(request);
拿到文件对象列表。
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存缓冲区,超过后写入临时文件
factory.setSizeThreshold(10240000);//10M
// 设置临时文件存储位置
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置单个文件的最大上传值
upload.setFileSizeMax(10002400000l);//100M
// 设置整个request的最大值
upload.setSizeMax(10002400000l);//1000M
upload.setHeaderEncoding("UTF-8");
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHH");
String time = formatter.format(new Date());
String day = time.substring(0, 7);
String timeDetail = time.substring(8);
String ftpDirectory = "H:\\upload\\"+day+"\\"+timeDetail;
try {
List<?> items = upload.parseRequest(request); FileItem item = null;
String fileName = null;
for (int i = 0 ;i < items.size(); i++){
item = (FileItem) items.get(i);
fileName = item.getName();
InputStream fis = item.getInputStream();
// 保存文件
if (!item.isFormField() && item.getName().length() > 0) {
this.uploadFileByApacheByBinary(ftpDirectory,fis,fileName);
fis.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
但是struts2的action拿request的内容
List<?> items = upload.parseRequest(request);
取不到,原因是struts2讲request处理过了,可以通过struts2的方式上传文件
通过2种方式模拟单个文件上传,效果如下所示
开发步骤如下:
1、新建一个web工程,导入struts2上传文件所需jar,如下图
目录结构
2、新建Action
第一种方式

package com.ljq.action; import java.io.File; import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial")
public class UploadAction extends ActionSupport{ private File image; //上传的文件
private String imageFileName; //文件名称
private String imageContentType; //文件类型 public String execute() throws Exception {
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
System.out.println("realpath: "+realpath);
if (image != null) {
File savefile = new File(new File(realpath), imageFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
ActionContext.getContext().put("message", "文件上传成功");
}
return "success";
} public File getImage() {
return image;
} public void setImage(File image) {
this.image = image;
} public String getImageFileName() {
return imageFileName;
} public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
} public String getImageContentType() {
return imageContentType;
} public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
} }

第二种方式

package com.ljq.action; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport { // 封装上传文件域的属性
private File image;
// 封装上传文件类型的属性
private String imageContentType;
// 封装上传文件名的属性
private String imageFileName;
// 接受依赖注入的属性
private String savePath; @Override
public String execute() {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
// 建立文件输出流
System.out.println(getSavePath());
fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName());
// 建立文件上传流
fis = new FileInputStream(getImage());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} catch (Exception e) {
System.out.println("文件上传失败");
e.printStackTrace();
} finally {
close(fos, fis);
}
return SUCCESS;
} /**
* 返回上传文件的保存位置
*
* @return
*/
public String getSavePath() throws Exception{
return ServletActionContext.getServletContext().getRealPath(savePath);
} public void setSavePath(String savePath) {
this.savePath = savePath;
} public File getImage() {
return image;
} public void setImage(File image) {
this.image = image;
} public String getImageContentType() {
return imageContentType;
} public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
} public String getImageFileName() {
return imageFileName;
} public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
} private void close(FileOutputStream fos, FileInputStream fis) {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println("FileInputStream关闭失败");
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
System.out.println("FileOutputStream关闭失败");
e.printStackTrace();
}
}
} }

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>
<!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
<constant name="struts.action.extension" value="do" />
<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默认的视图主题 -->
<constant name="struts.ui.theme" value="simple" />
<!--<constant name="struts.objectFactory" value="spring" />-->
<!--解决乱码 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
<constant name="struts.multipart.maxSize" value="10701096"/>
<!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
<constant name="struts.multipart.saveDir " value="d:/tmp" /> <package name="upload" namespace="/upload" extends="struts-default">
<action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package> <package name="upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.UploadAction2" method="execute">
<!-- 动态设置savePath的属性值 -->
<param name="savePath">/images</param>
<result name="success">/WEB-INF/page/message.jsp</result>
<result name="input">/upload/upload.jsp</result>
<interceptor-ref name="fileUpload">
<!-- 文件过滤 -->
<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
<!-- 文件大小, 以字节为单位 -->
<param name="maximumSize">1025956</param>
</interceptor-ref>
<!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
<interceptor-ref name="defaultStack" />
</action>
</package>
</struts>

上传表单页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head> <body>
<!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
<!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
<form action="${pageContext.request.contextPath}/upload2/upload2.do"
enctype="multipart/form-data" method="post">
文件:<input type="file" name="image">
<input type="submit" value="上传" />
</form>
<br/>
<s:fielderror />
</body>
</html>

显示结果页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>上传成功</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head> <body>
上传成功!
<br/><br/>
<!-- ${pageContext.request.contextPath} tomcat部署路径,
如:D:\apache-tomcat-6.0.18\webapps\struts2_upload\ -->
<img src="${pageContext.request.contextPath}/<s:property value="'images/'+imageFileName"/>">
<s:debug></s:debug>
</body>
</html>

struts2,action上传文件的更多相关文章
- 菜鸟学SSH(五)——Struts2上传文件
上传文件在一个系统当中是一个很常用的功能,也是一个比较重要的功能.今天我们就一起来学习一下Struts2如何上传文件. 今天讲的上传文件的方式有三种: 1,以字节为单位传输文件: 2,Struts2封 ...
- struts2文件上传时获取上传文件的大小
利用struts2框架上传文件时,如果想要获取上传文件的大小可以利用下面的方式进行: FileInputStream ins = new FileInputStream(file); if (ins. ...
- 利用Struts上传文件
在利用struts2完成上传文件到服务器时,遇到获取不到文件名 原因是在Action中的属性名没有和jsp中的属性名匹配 <%@ page language="java" i ...
- jquery ajax 上传文件
html:<!-- /.tab-pane --> <div class="tab-pane" id="head_portrait"> & ...
- 利用ajaxfileupload插件异步上传文件
html代码: <input type="file" id="imgFile" name="imgFile" /> js代码: ...
- struts2 jquery ajaxFileUpload 异步上传文件
网上搜集的,整理一下. 一.ajaxFileUpload 实现异步上传文件利用到了ajaxFileUpload.js这个文件,这是别人开发的一个jquery的插件,可以实现文件的上传并能够和strut ...
- springMvc 使用ajax上传文件,返回获取的文件数据 附Struts2文件上传
总结一下 springMvc使用ajax文件上传 首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回e ...
- ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案
摘要: ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案 在struts2应用中使用ueditor富文本编辑器上传图片或者附件时,即使配置 ...
- struts2上传文件添加进度条
给文件上传添加进度条,整了两天终于成功了. 想要添加一个上传的进度条,通过分析,应该是需要不断的去访问服务器,询问上传文件的大小.通过已上传文件的大小, 和上传文件的总长度来评估上传的进度. 实现监听 ...
随机推荐
- Cpython解释器支持的线程
因为Python解释器帮你自动定期进行内存回收,你可以理解为python解释器里有一个独立的线程,每过一段时间它起wake up做一次全局轮询看看哪些内存数据是可以被清空的,此时你自己的程序 里的线程 ...
- IOS开发代码分享之获取启动画面图片的string
http://www.jb51.net/article/55309.htm 本代码支持 iPhone 6 以下. 支持 iPhone 及 iPad ? 1 2 3 4 5 6 7 8 9 10 11 ...
- Linux内核学习之中断 中断本质【转】
转自:http://www.linuxidc.com/Linux/2011-11/47657.htm [中断概述] 中断本质上是一种特殊的电信号,由硬件设备发向处理器.异常和中断的不同是异常在产生时必 ...
- 【bzoj3439】KPM的MC密码
这题乍一看后缀相等很烦的样子…… 其实如果把字符串倒过来,那么相等的后缀就可以转化成前缀,前缀相等扔进trie就可以了. 剩下无非是Trie的树链kth,主席树随便维护就好. 注意一个串彻底结束才能打 ...
- [ Python - 5 ] 通过random模块生成随机字符串
import random checkcode = '' for i in range(4): if i == random.randint(0,3): current = chr(random.ra ...
- lua返回服务器信息
ngx.header.content_type = "text/plain"; ngx.say(tostring(ngx.var.request_uri));ngx.say(tos ...
- USACO1.3.2修理牛棚
在学习一段时间贪心并写了一些贪心题之后,又一次看到了农夫和牛幸福美满的生活故事(雾).嘛,闲话少说,上题目 在一个暴风雨的夜晚,农民约翰的牛棚的屋顶.门被吹飞了. 好在许多牛正在度假,所以牛棚没有住满 ...
- RPD Volume 172 Issue 1-3 December 2016 评论04 end
这一篇作为本期的结束是因为发现后面的一些基本上也是EPR有关的会议内容, Contribution of Harold M. Swartz to In VivoEPR and EPR Dosimetr ...
- [BZOJ5463][APIO2018]铁人两项(圆方树DP)
题意:给出一张图,求满足存在一条从u到v的长度大于3的简单路径的有序点对(u,v)个数. 做了上一题[HDU5739]Fantasia(点双连通分量+DP),这个题就是一个NOIP题了. 一开始考虑了 ...
- small test on 5.30 night T2
(题面写错了,应该是一条从b -> a 的边) 让我们设状态 (a,b,c) 表示存在一个点k,使得 dist(k,b) - dist(k,a) * 2 + 3 = c,显然这里的第三维可以压 ...