struts2之图片上传

本文介绍了三种图片上传方案,包括上传到Tomcat服务器、指定文件目录和存储到数据库。重点讲述了第二种方法,即上传到指定文件目录,并通过映射关系解耦上传文件与Tomcat的关联。文中详细讲解了如何创建图片上传界面、实现上传功能以及在ClzzAction和clzList中进行的相关配置,最后展示了XML配置和主页效果。

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

三种上传方案

1、上传到tomcat服务器 上传图片的存放位置与tomcat服务器的耦合度太高(不常用)
2、上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系
文件服务器
3、在数据库表中建立二进制字段,将图片存储到数据库 需要的内存太大
所以在以上三种方法中我们只完成第二种

先建立图片上传界面:
clzUpload:

<%@ 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="${result.cid }"><br>
	<input type="hidden" name="cname" value="${result.cname }"><br>
	<input type="hidden" name="cteacher" value="${result.cteacher }"><br>
	<input type="file" name="file">
	<input type="submit" value="ok">
</form>
</body>
</html>

然后在ClazzAction实现跳转至图片上传界面和上传图片的方法,在以往的基础上多加了一些属性,属性的命名规范和方法的具体作用在代码注释里

package com.zyc.crud.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ModelDriven;
import com.zyc.crud.dao.ClazzDao;
import com.zyc.crud.entity.Clazz;
import com.zyc.crud.util.BaseAction;
import com.zyc.crud.util.PageBean;

public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{

	private Clazz clz=new Clazz();
	private ClazzDao clazzDao=new ClazzDao();
	//这里的属性名要和name对应。
	private File file;
	//xxxFileName
	private String fileFileName;
	//xxxContentType
	private String fileContentType;
	/**
	 * 跳转上传图片的界面
	 * @return
	 */
	public String preUpload() {
			try {
				this.result= this.clazzDao.list(clz,null).get(0);
			} catch (InstantiationException | IllegalAccessException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return "preUpload";
	}
	/**
	 * 图片上传
	 * @return
	 */
	public String upload() {
		//存放到电脑中的路径
		String realDir="E:/T226";
		//存放到数据库中的路径
		String serverDir="/upload";
		try {
//			FileUtils.copyFile(file, new File(realDir+"/"+fileFileName));
			copyFile(file, new File(realDir+"/"+fileFileName));
			clz.setPic(serverDir+"/"+fileFileName);
			try {
				this.clazzDao.edit(clz);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
					| SQLException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	/**
	 * 利用缓冲流的技术进行拷贝
	 * @param source 选择的文件
	 * @param target 上传到哪里
	 * @throws IOException 
	 */
	public void copyFile(File source,File target) throws IOException {
		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);
		}
		out.close();
		in.close();
	}
	
	public String list() {
		PageBean pageBean=new PageBean();
		pageBean.setRequest(request);
		try {
			List<Clazz> list = this.clazzDao.list(clz, pageBean);
			request.setAttribute("clzlist",list);
			request.setAttribute("pageBean",pageBean);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "list";
		
	}
	/**
	 * 跳转编辑页面(新增修改页面)
	 */
	public String preSave() {
		if(clz.getCid()!=0) {
			try {
				this.result= this.clazzDao.list(clz,null).get(0);
			} catch (InstantiationException | IllegalAccessException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "preSave";
	}
	public String add() {
		try {
			this.clazzDao.add(clz);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
				| SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}
	
	public String edit() {
		try {
			this.clazzDao.edit(clz);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
				| SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}
	public String del() {
		try {
			this.clazzDao.del(clz);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
				| SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		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 getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
}

我们在clzList中也需要改一些东西:
clzList:

<%@ 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="/zking" 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>班级主界面</title>
</head>
<body>
<h2>班级主界面</h2>
	<form action="${pageContext.request.contextPath}/sy/clz_list.action"
		method="post">
		班级名:<input type="text" name="cname"> <input type="submit"
			value="确定">
			<!--  
			<input type="hidden" name="rows" value="10">
			<input type="hidden" name="page" value="2">
			<input type="hidden" name="pagination" value="false">-->
	</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="b">
			<tr>
				<td>${b.cid }</td>
				<td>${b.cname }</td>
				<td>${b.cteacher }</td>
				<td>
					<img style="height: 60px;width: 100px" src="${pageContext.request.contextPath}${b.pic}">
				</td>
				<td>
				<a href="${pageContext.request.contextPath}/sy/clz_preSave.action?cid=${b.cid }">修改</a>&nbsp;&nbsp;
				<a href="${pageContext.request.contextPath}/sy/clz_del.action?cid=${b.cid}">删除</a>&nbsp;&nbsp;
				<a href="${pageContext.request.contextPath}/sy/clz_preUpload.action?cid=${b.cid}">图片上传</a>
				</td>
			</tr>
		</c:forEach>
	</table>
	<z:page pageBean="${pageBean}"></z:page>

</body>
</html>

添加映射关系:
在这里插入图片描述
path为项目名在加上我们在clzAction定义的serverDir属性;
docBase为上传到电脑的路径

在这里插入图片描述
最后再配置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="/hello_*" class="com.zhuyuncong.web.HelloAction" method="{1}">
			<result name="success">/success.jsp</result>
		</action>
		<action name="/clz_*" class="com.zyc.crud.web.ClazzAction" method="{1}">
		<result name="list">/clzList.jsp</result>
		<result name="preSave">/clzEdit.jsp</result>
		<result name="preUpload">/clzUpload.jsp</result>
		<result name="toList" type="redirectAction">/clz_list</result>
		</action>
	</package>
</struts>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值