Struts2——(8)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——(8)struts2中文件的上传的更多相关文章
- iOS开发中文件的上传和下载功能的基本实现-备用
感谢大神分享 这篇文章主要介绍了iOS开发中文件的上传和下载功能的基本实现,并且下载方面讲到了大文件的多线程断点下载,需要的朋友可以参考下 文件的上传 说明:文件上传使用的时POST请求,通常把要上传 ...
- JavaWeb中文件的上传和下载
JavaWeb中文件的上传和下载 转自: JavaWeb学习总结(五十)——文件上传和下载 - 孤傲苍狼 - 博客园https://www.cnblogs.com/xdp-gacl/p/4200090 ...
- [原创]java WEB学习笔记72:Struts2 学习之路-- 文件的上传下载,及上传下载相关问题
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- 关于在Struts2框架下实现文件的上传功能
struts2的配置过程 (1)在项目中加入jar包 (2)web.xml中filter(过滤器)的配置 <?xml version="1.0" encoding=" ...
- Struts2基础学习(六)—文件的上传和下载
一.文件的上传 1.单个文件上传 Struts2使用拦截器完成了文件的上传,而且底层使用的也是FileUpload开源组件. 客户端注意事项: (1)method="post&qu ...
- 009 spring boot中文件的上传与下载
一:任务 1.任务 文件的上传 文件的下载 二:文件的上传 1.新建一个对象 FileInfo.java package com.cao.dto; public class FileInfo { pr ...
- Java中文件的上传与下载
文件的上传与下载主要用到两种方法: 1.方法一:commons-fileupload.jar commons-io.jar apache的commons-fileupload实现文件上传,下载 [u ...
- php中文件断点上传怎么实现?
1.使用PHP的创始人 Rasmus Lerdorf 写的APC扩展模块来实现(http://pecl.php.net/package/apc) APC实现方法: 安装APC,参照官方文档安装,可以使 ...
- SpringMVC中文件的上传(上传到服务器)和下载问题(一)
一.今天我们所说的是基于SpringMVC的关于文件的上传和下载的问题的解决.(这里所说的上传和下载都是上传到服务器与从服务器上下载文件).这里的文件包括我们常用的各种文件.如:文本文件(.txt), ...
- Struts2中文件的上传与下载
文件上传 1.jsp页面 <s:form action="fileAction" namespace="/file" method="POST& ...
随机推荐
- DC针对pipeline的优化
set_optimize_register true compile -ultra 调整pipleline各级的组合逻辑,使得各级组合逻辑的延迟跟接近 对非pipeline进行优化: regi ...
- 百度糯米iOSclient登录BUG
环境 设备:iphone5s 网络:WIFI App版本号: 操作步骤 1.进入登录界面 2.输入手机号 3.点击[获取验证码],等待接收验证码后 4.点击[X]退出登录界面 5.反复1-2-3,提示 ...
- xml 标准字符过滤
今天在代码里面看见一串非常奇怪的推断语句 if (c < 0x9 || c > 0x9 && c < 0xA || c > 0xA && c & ...
- Altium Designer如何移动选中的所有对象
用shift去选中, 快捷键M S移动整体
- [array] leetCode-26. Remove Duplicates from Sorted Array - Easy
26. Remove Duplicates from Sorted Array - Easy descrition Given a sorted array, remove the duplicate ...
- 【z08】乌龟棋
描述 小明过生日的时候,爸爸送给他一副乌龟棋当作礼物. 乌龟棋的棋盘是一行N个格子,每个格子上一个分数(非负整数).棋盘第1格是唯一的起点,第N格是终点,游戏要求玩家控制一个乌龟棋子从起点出发走到终点 ...
- freemarker导出图片到word
1.word模版制作: 在word中添加图片,第一步制作模板时,加入一张图片占位,然后打开xml文档,可以看到如下的一片base64编码后的代码: <w:binData w:name=" ...
- 闪回drop恢复表后sql运行计划异常
-----正常运行计划 set autotrace traceonly set linesize 1000 select /*+index(t idx_object_id)*/ * from t wh ...
- Xcode5新特性之注释
Xcode5新特性之注释 Xcode5在注释式文档方面也有进步,越来越象javadoc. Xcode4 参考一下教程 http://blog.chukong-inc.com/index.php/201 ...
- 使用Html5开发Android和iOS应用:HBuilder、Html5Plus、MUI
活动主题:五一巨献,问答有礼,105QB送给IT互联网界的劳动人民活动时间:4月30日晚上10点~5月2日晚上10点网址: http://ask.jiutianniao.com 2014年的时候,就 ...

