struts2的图片上传与拦截器

博客介绍了文件上传的三种方式,包括上传到tomcat服务器、指定文件目录和解耦与tomcat关系、存储到数据库,常用前两种。还展示了用第二种方式进行文件上传的代码,阐述了文件上传的底层原理,以及拦截器的两种实现方法和配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件上传的三种方式

1、上传到tomcat服务器
2、上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系
文件服务器
3、在数据库表中建立二进制字段,将图片存储到数据库

第一二种是常用的,而第三种搞那种数据少时,可以用。但是数据比较大的话,不适用

文件上传

我们这里的文件上传用第二种方式,在上一篇的基础上,我们在进行文件上传。
接下来我们看代码
ClazzAction

public class ClazzAction extends BaseAction implements ModelDriven<Clazz> {
	private ClazzDao clzDao = new ClazzDao();
	private Clazz clz = new Clazz();
	
	private File file;
	private String fileContentType;
	private String fileFileName;
	
	/**
	 * 查询所有
	 * @return
	 */
	public String list() {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(request);
		try {
			List<Clazz> list = this.clzDao.list(clz, pageBean);
			// this.result = this.clzDao.list(clz, pageBean);
			request.setAttribute("clzList", list);
			request.setAttribute("pageBean", pageBean);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "list";
	}
	
	/**
	 * 直接上传
	  * @return
	 */
	public String upload() {
		try {
			//注意:在Linux下是没有E盘的,Linux下只有一个盘符,那么意味着,当打包到Linux服务器的时候需要改动代码
			//这个时候通常是这么解决的,将targetPath对应目录串,配置到资源文件中,通过Properties类进行动态读取
			//那么当需要将项目发布到Linux服务器的时候,只需要改变xxx.properties文件中targetPath=/zking/T224/img
			//实际图片存储位置
			String targetDir = "D:/背景";
			//存到数据库中的地址
			String severPath = "/upload";
//			FileUtils.copyFile(file, new File(targetDir+"/"+fileFileName));
			copyFile(file, new File(targetDir+"/"+fileFileName));
			//注意:数据库存放时网络请求地址,而不是本地图片存放的地址
			clz.setPic(severPath+"/"+fileFileName);
			this.clzDao.edit(clz);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	/**
	 * FileUtils.copyFile的底层,并且通过缓冲区进行了增强
	 * @param source
	 * @param target
	 * @throws Exception
	 */
	public void copyFile(File source,File target) throws Exception{
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));
		byte[] bbuf = new byte[1024];
		int len = 0;
		while((len = in.read(bbuf))!=-1) {
			out.write(bbuf, 0, len);
		}
		in.close();
		out.close();
	}
	
	/**
	 * 跳转文件上传页面
	 * @return
	 */
	public String preUpload() {
		try {
			Clazz c = this.clzDao.list(clz, null).get(0);
			request.setAttribute("clz",c);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "toUpload";
	}

	/**
	 * 跳转新增修改页面的通用方法
	 * 
	 * @return
	 */
	public String preSave() {
		if(clz.getCid()!=0) {
			try {
				Clazz c = this.clzDao.list(clz, null).get(0);
				request.setAttribute("clz",c);
			} catch (InstantiationException | IllegalAccessException | SQLException e) {
				e.printStackTrace();
			}
		}
		return "preSave";
	}
	
	/**
	 * 新增
	 * @return
	 */
	public String add() {
		try {
			result = this.clzDao.add(clz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}

	/**
	 * 修改
	 * @return
	 */
	public String edit() {
		try {
			this.clzDao.edit(clz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	/**
	 * 删除
	 * @return
	 */
	public String del() {
		try {
			this.clzDao.del(clz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}

	@Override
	public Clazz getModel() {
		return clz;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
}

struts-sy.xml中配置好

<action name="/clz_*" class="com.lst.crud.web.ClazzAction" method="{1}">
	<result name="list">/clzList.jsp</result>
	<result name="preSave">/clzEdit.jsp</result>
	<result name="toList" type="redirectAction" >/clz_list</result>
	<result name="toUpload">/upload.jsp</result>
</action>

创建jsp界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片上传</title>
</head>
<body>
	<form action="${pageContext.request.contextPath}/sy/clz_upload.action" method="post" enctype="multipart/form-data">
		<input type="hidden" name="cid" value="${clz.cid }"><br>
 		<input type="hidden" name="cname" value="${clz.cname }"><br>
		<input type="hidden" name="cteacher" value="${clz.cteacher }"><br>
		<!-- 注意:name对应的值决定了,子控制器action属性的命名 -->
		<input type="file" name="file" >
		<input type="submit">
	</form>
</body>
</html>

在你的本地servers的server.xml加一条代码

<Context path="struts/upload" docBase="E:/temp/T224/"/>

效果展示:
在这里插入图片描述

文件上传的底层原理

/**
 * FileUtils.copyFile的底层,并且通过缓冲区进行了增强
 * @param source
 * @param target
 * @throws Exception
 */
public void copyFile(File source,File target) throws Exception{
	BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
	BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));
	byte[] bbuf = new byte[1024];
	int len = 0;
	while((len = in.read(bbuf))!=-1) {
		out.write(bbuf, 0, len);
	}
	in.close();
	out.close();
}

拦截器Interceptor

拦截器的两种实现方法

implements Interceptor
extends AbstractInterceptor

OneInterceptor拦截器

package com.lst.crud.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class OneInterceptor implements Interceptor {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		System.out.println("=============OneInterceptor=============1");
		String invoke = arg0.invoke();
		System.out.println("=============OneInterceptor=============2");
		return invoke;
	}

}

TwoInterceptor拦截器

package com.lst.crud.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class OneInterceptor implements Interceptor {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		System.out.println("=============TwoInterceptor=============1");
		String invoke = arg0.invoke();
		System.out.println("=============TwoInterceptor=============2");
		return invoke;
	}

}

struts-sy.xml中配置好

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<!-- /user/bookAction?methodName=list
		/sy/bookAction?methodName=list
	 -->
	 
	<package name="sy" extends="base" namespace="/sy">
		<interceptors>
			<interceptor name="one" class="com.lst.crud.interceptor.OneInterceptor"></interceptor>
			<interceptor name="two" class="com.lst.crud.interceptor.TwoInterceptor"></interceptor>
		</interceptors>
		
		<action name="/demo_*" class="com.lst.web.HelloAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		
		<action name="/stack_*" class="com.lst.test.DemoAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		
		<action name="/clz_*" class="com.lst.crud.web.ClazzAction" method="{1}">
			
			<interceptor-ref name="one"></interceptor-ref>
			<interceptor-ref name="two"></interceptor-ref>
		
			<result name="list">/clzList.jsp</result>
			<result name="preSave">/clzEdit.jsp</result>
			<result name="toList" type="redirectAction" >/clz_list</result>
			<result name="toUpload">/upload.jsp</result>
		</action>
		
	</package>
</struts>

然后我们运行,正常的话会出现下图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值