文件上传功能与拦截器原理

文件上传方案:

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

整个功能的核心

ClazzAction

package com.wangshaoyang.web;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.List;
import com.opensymphony.xwork2.ModelDriven;
import com.wangshaoyang.dao.ClazzDao;
import com.wangshaoyang.entity.Clazz;
import com.wangshaoyang.util.PageBean;

public class ClazzAction extends BaseAction implements ModelDriven<Clazz> {
	private ClazzDao clazzDao = new ClazzDao();
	private Clazz clz = new Clazz();
	private File file;
	private String fileContentType;
	private String fileFileName;
	/**
	 * 
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public String list() throws InstantiationException, IllegalAccessException, SQLException {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(request);
		List<Clazz> list = this.clazzDao.list(clz, pageBean);
		// this.result = this.clazzDao.list(clz, pageBean);
		request.setAttribute("clzList", list);
		request.setAttribute("pageBean", pageBean);
		return "list";
	}
	
	/**
	 * 直接上传图片
	 * @return
	 * @throws Exception 
	 */
//	public String upload() throws Exception {
//		//注意:在linux下是没有E盘的,Linux下只有一个盘,那么意味着,当打包到Linux服务器的时候需要改动代码
//		//这个时候通常是那么解决的,将targetDir对用目录串,配置到资源文件中,通过Properties类进行动态读取
//		//那么需要将项目发布到Linux服务器的时候,只需要改变XXX.properties文件中的targetDir....(根目录)
//		
//		//实际图片存储的位置
//		String targetDir = "E:/temp";
		存到数据库中的地址
//		String severPath = "/upload";
//		FileUtils.copyFile(file, new File(targetDir+"/"+fileFileName));
		copyBufFile(file, new File(targetDir+"/"+fileFileName));
		注意:数据库存放的是网络请求地址,而不是本地图片存放地址
//		clz.setPic(severPath+"/"+fileFileName);
//		this.clazzDao.edit(clz);
//		return "toList";
//	}
	/**
	 * 跳转文件上传页面
	 * @return
	 */
	public String preUpload() {
		try {
			Clazz c = this.clazzDao.list(clz, null).get(0);
			request.setAttribute("clz", c);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toUpload";
	}
	/**
	 * 
	 * @param source
	 * @param target
	 * @throws Exception
	 */
	public void copyBufFile(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
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public String preSave() throws InstantiationException, IllegalAccessException, SQLException {
		if(clz.getCid() != 0) {
			Clazz c = this.clazzDao.list(clz, null).get(0);
			request.setAttribute("clz", c);
		}
		return "preSave";
	}
	
	/**
	 * 新增
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	public String add() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		result = this.clazzDao.add(clz);
		return "toList";
	}
	
	/**
	 * 删除
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	public String del() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		this.clazzDao.del(clz);
		return "toList";
	}
	/**
	 * 修改
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public String edit() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		this.clazzDao.edit(clz);
		return "toList";
	}
	@Override
	public Clazz getModel() {
		// TODO Auto-generated method stub
		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

<?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>
	<package name="sy" extends="base" namespace="/sy">
		
		<action name="/clz_*" class="com.wangshaoyang.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>
	</package>	
</struts>
在你的本地servers的server.xml加上这行代码:
<Context docBase="E:/temp/" path="/Strtus_crud/wangshaoyang"/>
写一个jsp界面
upload.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>Insert title here</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>
clzList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="/z"  prefix="z" %>
<!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>Insert title here</title>
</head>
<body>
<h2></h2>
	<br>
	<form action="${pageContext.request.contextPath}/sy/clz_list.action"
		method="post">
		班级名:<input type="text" name="cname"> <input type="submit"
			value="确定">
	</form>
	<a href="${pageContext.request.contextPath}/sy/clz_preSave.action">增加</a>
	<table border="1" width="100%">
		<tr>
			<td>编号</td>
			<td>班级名</td>
			<td>教员</td>
			<td>图片</td>
			<td>操作</td>
		</tr>
		<c:forEach items="${clzList }" var="c">
			<tr>
				<td>${c.cid }</td>
				<td>${c.cname }</td>
				<td>${c.cteacher }</td>
				<td>
					<img alt="" style="width: 60px;height: 60px;" src="${pageContext.request.contextPath}${c.pic }">
				</td>
				<td>
					<a href="${pageContext.request.contextPath}/sy/clz_preSave.action?cid=${c.cid}">修改</a>
					&nbsp;
					<a href="${pageContext.request.contextPath}/sy/clz_del.action?cid=${c.cid}">删除</a>
					&nbsp;<a href="${pageContext.request.contextPath}/sy/clz_preUpload.action?cid=${c.cid}">上传</a>
				</td>
			</tr>
		</c:forEach>
	</table>
	<z:page pageBean="${pageBean }"></z:page>
</body>
</html>

这样就可以看到文件上传的效果了
两个底层:

/**
	 * FileUtils.copyFile的底层,并且通过缓冲区进行了增强
	 * @param source
	 * @param target
	 * @throws Exception
	 */
	public void copyBufFile(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();
	}
拦截器 OneInterceptor
package com.wangshaoyang.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=====");
		String invoke = arg0.invoke();
		System.out.println("====OneInterceptor=====");
		return invoke;
	}
}
TwoInterceptor
package com.wangshaoyang.Interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class TwoInterceptor implements Interceptor{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7433091992916683936L;

	@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=====");
		String invoke = arg0.invoke();
		System.out.println("====TwoInterceptor=====");
		return invoke;
	}	
}

我们首先定义一个拦截器

<?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>
	<package name="sy" extends="base" namespace="/sy">
	<interceptors>
		<interceptor name="one" class="com.wangshaoyang.crud.interceptor.OneInterceptor"></interceptor>
		<interceptor name="two" class="com.wangshaoyang.crud.interceptor.TwoInterceptor"></interceptor>
	</interceptors>
		<action name="/demo_*" class="com.wangshaoyang.web.HelloAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		<action name="/stack_*" class="com.wangshaoyang.test.DemoAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		<action name="/clz_*" class="com.wangshaoyang.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>

然后我来运用下

<?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>
	<package name="sy" extends="base" namespace="/sy">
	<interceptors>
		<interceptor name="one" class="com.liyi.crud.interceptor.OneInterceptor"></interceptor>
		<interceptor name="two" class="com.liyi.crud.interceptor.TwoInterceptor"></interceptor>
	</interceptors>
		<action name="/demo_*" class="com.liyi.web.HelloAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		<action name="/stack_*" class="com.wangshaoyang.test.DemoAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		<action name="/clz_*" class="com.wangshaoyang.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>

今天就更新到这里
喜欢的可以关注我
不定时更新

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听晚风续过晚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值