Struts之文件上传

Struts之文件上传在Struts之增删改查的基础上进行开发

三种方式:

一,上传到tomcat服务器 

1,自己的电脑,项目在哪里,图片就在哪里

2,云服务器:是没有CDEF盘的,只有/根目录(阿里云、腾讯云、西部数码云)

二,(用的多)上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系文件服务器和web服务器通常是一个,但是文件目录与Tomcat目录肯定不是同一个

三,在数据库表中建立二进制字段,将图片存储到数据库(安全性比第二种高)

主要讲第二种:

注意点:1,上传文件的界面   enctype--"multipart/form--data"   type--"file"

开发步骤:

 1,前端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="${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="img"><br>
		<input type="submit">
	</form>
</body>
</html>

2,编写子控制器并封装参数

	/**
	 * 按照指定的格式去接受参数变量
	 * 1.上传的文件
	 * 2.上传的文件名
	 * 3.上传的文件类别
	 */
	private File img;
	private String imgFileName;
	private String imgContentType;
 
	public File getImg() {
		return img;
	}
 
	public void setImg(File img) {
		this.img = img;
	}
 
	public String getImgFileName() {
		return imgFileName;
	}
 
	public void setImgFileName(String imgFileName) {
		this.imgFileName = imgFileName;
	}
 
	public String getImgContentType() {
		return imgContentType;
	}
 
	public void setImgContentType(String imgContentType) {
		this.imgContentType = imgContentType;
	}
	
	/**
	 * 跳转到文件上传界面
	 */
	public String preUpload() throws Exception {
		this.result = this.clzDao.list(clz, null).get(0);
		this.req.setAttribute("result", result);
		return "upload";
	}
	
	/**
	 * 上传图片的方法
	 */
	public String upload() throws Exception {
//		img代表客户选择的文件或图片,接下来要将图片上传到其他地方
		String destDir="F:/ruanjian/upload/";
    	String serverDir="/uploadImages";
//    	源文件考到目的地
    	FileUtils.copyFile(img, new File(destDir+"/"+imgFileName));
    	//将图片加到数据库
    	//数据库保存的值是:/uploadImages/xx.png
    	//图片是在:F:/ruanjian/upload/
    	//访问:http://localhost:8080/struts/uploadImages/xx.png
    	clz.setPic(serverDir+"/"+imgFileName);
    	this.clzDao.edit(clz);
		return TOLIST;
	}

.3,配置子控制器

<result name="upload">/upload.jsp</result>

4,selver.xml中做路径配置

<Context docBase="F:/y1/img" path="/uploadImages"/>

5,前端主页面jsp图片显示与增加操作列 

效果展示:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值