本文主要两种方式,一:通过 FileUtils.copyFile(file, savefile);方法复制;二:通过字节流方式复制

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 framework -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter> <filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter> <filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>*.do</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping> <filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

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="uploadFile" extends="struts-default">
<action name="upload" class="com.nn.upload.UploadAction" method="upload">
<result name="success">/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
<!--方法二 -->
<package name="uploadFile2" extends="struts-default">
<action name="upload2" class="com.nn.upload.UploadAction" method="uploadByStream">
<param name="allowTypes">.bmp,.png,.gif,.jpeg,.jpg</param>
<param name="savePath">/upload</param> <!-- 保存的真实路径 -->
<result name="success">/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>

struts.properties

struts.multipart.parser=jakarta
struts.multipart.saveDir=/temp
struts.multipart.maxSize=
struts.i18n.encoding=utf-
struts.locale=zh_CN
struts.action.extension=do
struts.custom.i18n.resources=globalMsg

UploadAction.java 主要代码

public class UploadAction extends ActionSupport {
private File file;
private String fileName;
private String fileType;
// 第二种方法中接受依赖注入的属性
private String savePath;
private String allowTypes; /**
* 第一种方法,使用FileUtils从temp中复制到相关路径下面,结束后temp中的文件自动被清楚
* @return
*/
public String upload() {
String realpath = ServletActionContext.getServletContext().getRealPath("/upload");
if (file != null) {
String name = this.getFileName().substring();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
this.setFileName(df.format(new Date())+name); //文件名字+日期
File savefile = new File(new File(realpath), this.getFileName());
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
try {
FileUtils.copyFile(file, savefile);
} catch (IOException e) {
e.printStackTrace();
}
ActionContext.getContext().put("message", "文件上传成功!");
}
return "success";
} /**
* 第二站方式,通过字节流来复制
* @return
*/
public String uploadByStream(){
// 判断是否允许上传
String filterResult = findFileType(this.getAllowTypes().split(","));
if (filterResult != null) {
ActionContext.getContext().put("typeError","您要上传的文件类型不正确");
return filterResult;
} // 以服务器的文件保存地址和原文件名建立上传文件输出流
FileOutputStream fos;
FileInputStream fis;
String realpath = ServletActionContext.getServletContext().getRealPath(this.getSavePath());
try {
String name = this.getFileName().substring();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
this.setFileName(df.format(new Date())+name); //文件名字+日期
realpath = realpath +"\\"+this.getFileName();
fos = new FileOutputStream(realpath);
fis = new FileInputStream(this.getFile());
byte[] buffer = new byte[];
int len = ;
while ((len = fis.read(buffer)) > ) {
fos.write(buffer, , len);
}
fos.close();
fis.close();
return SUCCESS;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return INPUT;
}
public String findFileType(String[] types) {
String fileType = this.getFileType();
for (String type : types) {
if (type.equals(fileType)) {
return null;
}
}
return INPUT;
} //省略get set 方法
}

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function check(){
var file = document.getElementById("file");
if(file != null){
var fileType = file.value.substr(file.value.lastIndexOf(".")).toLowerCase(); //截取类型,如.jpg
var fileName = file.value.substr(file.value.lastIndexOf("\\")); //截取文件名字,如:/01.png
document.getElementById("fileName").value = fileName;
document.getElementById("fileType").value = fileType;
return true;
}
alert("请选择文件");
return false;
}
</script>
</head> <body>
<p>stuts 文件上传实例 </p>
${requestScope.typeError}
<!-- 第一种方式上传链接:
<form action="/upload.do" method="post" enctype="multipart/form-data" onsubmit="return check();">
-->
<form action="/upload2.do" method="post" enctype="multipart/form-data" onsubmit="return check();">
上传文件:<input type="file" name="file" /><input type="submit" value="上传"/>
<input type="hidden" name="fileType" id="fileType"/>
<input type="hidden" name="fileName" id="fileName"/>
</form> </body>
</html>

success.jsp

 <body>
${requestScope.message}<br>
文件名称:<input type="text" value="<s:property value="fileName"/>"/><br>
文件为:<img src="${pageContext.request.contextPath}/<s:property value="'upload/'+fileName"/>"><br>
<s:debug></s:debug>
</body>

源码下载地址:http://download.csdn.net/detail/u011518709/7896593

struts2的单个文件上传的更多相关文章

  1. Struts2 单个文件上传/多文件上传

    1导入struts2-blank.war所有jar包:\struts-2.3.4\apps\struts2-blank.war 单个文件上传 upload.jsp <s:form action= ...

  2. sruts2:单个文件上传,多个文件上传(属性驱动)

    文件上传功能在Struts2中得到了很好的封装,主要使用fileUpload上传组件. 1. 单个文件上传 1.1 创建上传单个文件的JSP页面.显示提交结果的JSP页面 uploadTest1.js ...

  3. Struts2 之 实现文件上传和下载

    Struts2  之 实现文件上传和下载 必须要引入的jar commons-fileupload-1.3.1.jar commons-io-2.2.jar 01.文件上传需要分别在struts.xm ...

  4. Struts2 之 实现文件上传(多文件)和下载

    Struts2  之 实现文件上传和下载 必须要引入的jar commons-fileupload-1.3.1.jar commons-io-2.2.jar 01.文件上传需要分别在struts.xm ...

  5. spring mvc文件上传(单个文件上传|多个文件上传)

    单个文件上传spring mvc 实现文件上传需要引入两个必须的jar包    1.所需jar包:                commons-fileupload-1.3.1.jar       ...

  6. [转]Struts2多个文件上传

    转载至:http://blog.csdn.net/hanxiaoshuang123/article/details/7342091 Struts2多个文件上传多个文件上传分为List集合和数组,下面我 ...

  7. 笨鸟先飞之Java(一)--使用struts2框架实现文件上传

    无论是.net还是Java,我们最常接触到的就是文件的上传和下载功能,在Java里要实现这两个经常使用功能会有非常多种解决方案,可是struts2的框架却能给我们一个比較简单的方式,以下就一起来看吧: ...

  8. springboot文件上传: 单个文件上传 和 多个文件上传

    单个文件上传 //文件上传统一处理 @RequestMapping(value = "/upload",method=RequestMethod.POST) @ResponseBo ...

  9. 4.struts2中的文件上传,下载

    Struts2中文件的上传下载,是借用commons里面的包实现文件的上传,需要导入两个jar commons-fileupload-1.2.2.jar commons-io-2.0.1.jar 实现 ...

随机推荐

  1. Unity2016 Unity3D开发VR游戏的经验

    http://z.youxiputao.com/articles/8313 在4月12日的Unite 2016大会上,暴风魔镜高级产品经理吴涛分享他用Unity3D开发VR游戏的经验,以下为分享实录: ...

  2. [3dmax教程] 人物+骨骼+蒙皮+动画教程

    人物+骨骼+蒙皮+动画完整教程选准备好一个人,做人的方法我在这里就不做了,大家可以学都用poser来做一个.  在大腿里建立4根骨骼! 在前视图中移动如图所示位置! 做一段简单的骨骼向前伸的动画,做4 ...

  3. perl C/C++ 扩展(一)

    通过h2xs 中间件,我们可以快速的使用c或则C++ 库来实现perl 扩展功能 第一讲:跑通hello world 程序******************************我们使用命令:h2 ...

  4. jar工具的使用

  5. F - Balanced Number

    #include <iostream> #include <algorithm> #include <cstring> #include <cstdio> ...

  6. tensorflow:实战Google深度学习框架第四章01损失函数

    深度学习:两个重要特性:多层和非线性 线性模型:任意线性模型的组合都是线性模型,只通过线性变换任意层的全连接神经网络与单层神经网络没有区别. 激活函数:能够实现去线性化(神经元的输出通过一个非线性函数 ...

  7. Codeforces Round #396 (Div. 2) E

    Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n - 1 undirec ...

  8. 使用tmodjs

    1.安装 npm install -g tmodjs 2.配置 我的模板都放在tpl文件夹中,htmls用于存放模板页面,每一个后缀名都是.html,而build用于存放编译后输出的模板js. 如果不 ...

  9. [已读]JavaScript语言精髓与编程实践

    推荐第二章的内容,关于表达式和运算符的内容很独到.

  10. Github开源项目单

    以下涉及到的数据统计与 2019 年 5 月 1 日 12 点,数据来源:https://github.com/trending/java?since=monthly . 下面的内容从 Java 学习 ...