其他分享
首页 > 其他分享> > 拦截器与文件上传

拦截器与文件上传

作者:互联网

文章目录

1.三种上传方案

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

这里我使用了第二种1、利用struts拦截器完成文件上传功能,接下来和大家讲解下。

2.文件上传

首先写一个文件上传的方法
classAction.java


	/**
	 * 跳转文件上传页面
	 * @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";
	}
	
第二步:配置一下
struts-sy.xml
	
		<action name="/clz_*" class="com.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>
最后写jsp界面
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="/zrh" 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>
	<form action="${pageContext.request.contextPath }/sy/clz_list.action" method="post">
		<!-- <input type="hidden" name="paginaction" value="false"> -->
		班级名:<input type="text" name="cname">
			<input type="submit" value="确定">
	</form>
	<a href="${pageContext.request.contextPath }/sy/clz_preSave.action">增加</a>
	<table border="1px" width="90%">
		<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;&nbsp;
					<a href="${pageContext.request.contextPath }/sy/clz_del.action?cid=${c.cid}">删除</a>&nbsp;&nbsp;
					<a href="${pageContext.request.contextPath }/sy/clz_preUpload.action?cid=${c.cid}">上传</a>&nbsp;&nbsp;
				</td>
			</tr>
		</c:forEach>
	</table>
	
	<z:page pageBean="${pageBean }"/>


</body>
</html>
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 }">
	<input type="hidden" name="cname" value="${clz.cname }">
	<input type="hidden" name="cteacher" value="${clz.cteacher }">
	<input type="file" name="file">
	<input type="submit" >
</form>
</body>
</html>

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

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

这样就写完了
效果为:
在这里插入图片描述

3、拦截器原理

文件上传的底层原理
首先自己定义一个带缓冲区流对象

/**
	 * 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();
	}

// 将这个注释 FileUtils.copyFile(file, new File(targeDir+"/"+fileFileName));
替换为自己写的 copyBufFile(file, new File(targeDir+"/"+fileFileName));

然后写两个拦截器
OneInterceptor拦截器

package com.crud.interceptor;

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

public class OneInterceptor implements Interceptor{
//实现OneInterceptor的三个方法
	@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.crud.interceptor;

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

public class TwoInterceptor implements Interceptor{
//实现TwoInterceptor的三个方法
	@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;
	}
	

}


第三步:

  <!-- 定义拦截器 -->

<interceptors>

            <interceptor name="oneInterceptor" class="com.javaxl.interceptor.OneInterceptor"></interceptor>

            <interceptor name="twoInterceptor" class="com.javaxl.interceptor.TwoInterceptor"></interceptor>

        </interceptors>

 
	<!-- 应用拦截器 -->
		<action name="/clz_*" class="com.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>
		

最后运行,结果为
在这里插入图片描述

标签:文件,拦截器,jsp,clz,new,上传,public
来源: https://blog.csdn.net/Zhangrunhong/article/details/95744979