通过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;@Overridepublic 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之单个文件上传(特别推荐)相关推荐

  1. struts2之单个文件上传

    通过2种方式模拟单个文件上传,效果如下所示 开发步骤如下: 1.新建一个web工程,导入struts2上传文件所需jar,如下图 目录结构 2.新建Action 第一种方式 package com.l ...

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

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

  3. Struts2学习8--文件上传(单个文件上传)

    一.依赖 Struts2利用第三方文件上传框架:(Myeclispse已配置)进行封装,没有jar需自己加上. Library                                      ...

  4. struts2.0实现文件上传

    首先,引入jar包.除了 Struts2.0的几个核心jar包外,还需要额外引入commons-fileupload.jar和commons-io.jar. 引入这两个包的时候,似乎版本也是一个比较重 ...

  5. 【汇总】flash单个文件上传

    之前有朋友给我发送email,询问我是否有单个文件上传的源代码,因为当时写这个好像是在09年,所以放哪了一时也没找着.后来整理硬盘的时候,找到了源码,所以决定来个汇总(之前写过的关于flash+js上 ...

  6. struts2完美实现文件上传和下载

    ## struts2完美实现文件上传和下载 ## 第一步:在webx项目lib目录下加入struts.jar包 asm-3.3.jar asm-commons-3.3.jar asm-tree-3.3 ...

  7. struts2教程--实现文件上传下载

    Struts2文件上传下载 一.Struts2文件上传 提供 FileUpload 拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容 fileUpload拦截 ...

  8. Struts2框架--学习笔记(下):OGNL表达式、值栈操作、拦截器、struts2标签、文件上传

    一.OGNL概述:OGNL是一种表达式 (1)在struts2中操作值栈数据. (2)一般把ognl在struts2中操作,和struts2标签一起使用操作值栈. (3)ognl不是strut2的一部 ...

  9. 在Struts2中实现文件上传(二)

    发布运行应用程序,在浏览器地址栏中键入:http://localhost:8080/Struts2_Fileupload/FileUpload.jsp,出现图示页面:   清单7 FileUpload ...

最新文章

  1. xmanager破解待验证
  2. mysql buff cache_Centos7 cache/buff过高处理方法
  3. 环境变量PATH 、mv 命令 、cp 命令和 查看文档相关的命令
  4. internal server error怎么解决_MAC中MySQL添加my.cnf和PID file解决方案
  5. $unit编译单元声明
  6. vue中的v-text指令之Vue知识点归纳(二)
  7. 华为路由器时间同步_4G网络变WIFI,华为4G路由2 Pro让上网变得更简单
  8. [FZYZOJ 1002] 雨天
  9. Python 音频调整音量(附代码) | Python工具
  10. ”教你如何抓住短视频时代风口,进行流量红利变现
  11. matlab qpsk代码 博客,完整版QPSK调制原理及matlab程序实现
  12. 表格标签-表格基本结构
  13. 微软bi报表服务器,为 Power BI 报表服务器创建 Power BI 报表
  14. pythonsin怎么表示_Python numpy.sin()用法及代码示例
  15. 我们为什么用GO语言来做区块链?
  16. Linux系统下运行QT视频播放器示例程序(Media Player Example )
  17. Unity3D离线版数字地球实现
  18. 美观又实用,纯 CSS 悬浮菜单让网站更加出色
  19. 常用的功能测试点有哪些?
  20. 【转】DDS格式,以及打开方式

热门文章

  1. wxWidgets:wxSearchCtrl类用法
  2. wxWidgets:wxFileDirPickerEvent类用法
  3. wxWidgets:wxMBConv概述
  4. boost::regex模块实现将 C++ 文件转换为语法突出显示的 HTML的测试程序
  5. boost::mpl::size相关的测试程序
  6. GDCM:gdcm::Version的测试程序
  7. Boost:connect pair连接对测试程序
  8. ITK:分段线性曲线的数据结构
  9. ITK:从体积生成切片
  10. VTK:几何对象之PolygonIntersection