struts2单个文件上传的两种实现方式
发布时间:2023-04-23 05:33:30
通过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>


猜你喜欢
- 实践过程效果代码public partial class Form1 : Form{ public Form1()
- 定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。类型:创建类模式类图:四个要素产品类:一般是一个较为复杂的对
- 本文实例为大家分享了SpringMVC实现上传下载文件的具体代码,供大家参考,具体内容如下一、SpringMVC专门提供了CommonsMu
- 本文介绍了Java中常见死锁与活锁的实例详解,分享给大家,具体如下:顺序死锁:过度加锁,导致由于执行顺序的原因,互相持有对方正在等待的锁资源
- Android程序编码过程中,回调无处不在。从最常见的Activity生命周期回调开始,到BroadcastReceiver、Service
- 一、插入数据主键ID获取一般我们在做业务开发时,经常会遇到插入一条数据并使用到插入数据的ID情况。如果先插入在查询的话需要多一次sql查询,
- 很多朋友在下载文件的时候,经常会发现网站提供了MD5校验码,其实这个MD5码的作用就是当你下载文件好了之后,拿你下载好的文件的MD5校验码,
- 本文实例为大家分享了java实现简单单链表的具体代码,供大家参考,具体内容如下一、定义:单链表是一种链式存取的数据结构,用一组地址任意的存储
- Android onKeyDown监听返回键无效的解决办法当我们的Activity继承了TabActivity,在该类中重写on
- 使用jni进行opencv开发可以快速地将PC端的opencv代码移植到手机上,但是如何在android studio下进行配置,网上几乎找
- 字符串采用unicode编码的方式时,计算字符串长度的方法找出UNICODE编码中的汉字的代表的范围“\u4E00” 到“\u9FBB”之间
- Spring Boot 项目之热部署配置前言所谓热部署,简单来说,就是代码修改后不需重启项目就可自动加载出新的内容。注意:热部署在 debu
- 题目描述:一个农夫带着一匹狼、一只羊、一颗白菜要过河,只有一条船而且农夫每次最多只能带一个动物或物品过河,并且当农夫不在的时候狼会吃羊,羊会
- 按行读取文件package test; import java.io.*; import java.util.*; public class
- 开发环境: IDEA 2022.1.41. 概述虽然webservice这块使用很少,但在局域网作服务还是相当不错。今天突生想法,想做一个来
- 本篇文章主要来讲解怎样绘制游戏触摸轨迹的曲线图。 &nb
- 为什么需要互斥量在多任务操作系统中,同时运行的多个任务可能都需要使用同一种资源。这个过程有点类似于,公司部门里,我在使用着打印机打印东西的同
- 一、安装插件1.1直接用离线安装,将安装包拖到 IDEA窗口就安装好了,需要重启IDEA生效 (推荐)1.2 直接在idea上下JFormD
- 前言:文件的上传和下载在日常开发中很是常见,那么这一功能是如何实现的呢,下面我给大家介绍一下实现条件:1、需要一个form标签,method
- 学习过java基础,最近趁着大量课余时间想学习Android开发。百度很多资料Android studio,由Google开发的开发工具,那