本文主要两种方式,一:通过 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. 浅谈C# String对象

    本文介绍C#中的string是一个引用类型,C# String对象是存放在堆上,而不是堆栈上的,因此,当把一个字符串变量赋给另一个字符串时,会得到对内存中同一个字符串的两个引用. AD:WOT2015 ...

  2. [Xcode 实际操作]八、网络与多线程-(7)使用MessageUI框架,创建并发送一封带有附件的邮件

    目录:[Swift]Xcode实际操作 本文将演示如何使用MessageUI框架,创建并发送一封带有附件的邮件. 使用邮件编辑视图控制器(MFMailComposeViewController)实现邮 ...

  3. Modulation of Lipid Metabolism by Celastrol (文献分享一组-赵倩倩)

    文献名:Modulation of Lipid Metabolism by Celastrol (雷公藤红素对脂质代谢调节作用的研究) 期刊名:Journal of Proteome Research ...

  4. 在接口的实现类里使用@Override注解报错

    问题分析 @Override注解用来检测子类对父类或接口的方法的重写是否正确,但有一次我在Eclipse里对接口的实现类里使用@Override注解却报错,不过在父类的子类里使用该注解却是正常的. 百 ...

  5. 三维BFS Poj 2251

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

  6. 洛谷P2473||bzoj1076 [SCOI2008]奖励关

    https://www.luogu.org/problemnew/show/P2473 https://www.lydsy.com/JudgeOnline/problem.php?id=1076 不会 ...

  7. Java EE学习笔记(五)

    Spring事务管理 1.Spring事务管理概述 1).在实际开发中,操作数据库时都会涉及到事务管理问题,为此Spring提供了专门用于事务处理的API.(事务特性:ACID,原子性,一致性,隔离性 ...

  8. 转 php include

    http://www.w3school.com.cn/php/php_includes.asp PHP include 实例 例子 1 假设我们有一个名为 "footer.php" ...

  9. Django 使用allauth报错

    一:报错 RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_labe ...

  10. Unix高级环境编程之fcntl函数

    #include <fcntl.h> int fcntl(int fd, int cmd, ...) fcntl功能 复制一个现有的描述符 (cmd = F_DUPFD) ##### 返回 ...