struts文件上传

文件上传的三种方案

1.上传到tomcat服务器

2.上传到指定文件目录,添加服务器与真实目录的映射关系

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

注意:

①上传文件界面:enctype="multipart/form-data"    type="file"

②struts必须按照指定的格式去接收参数变量

1、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="${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">
<input type="submit">
</form>
</body>
</html>

2.ClzAction 

   先调用list方法查询到单条数据

   然后调用修改的方法对图片路径进行修改

/**
	 * 按照指定的格式接受参数变量
	 * 1.上传图片、2上传的文件名  3上传的文件类别
	 */
	private File img;
	private String imgFileName;
	private String imgContentType;


	public Clz getClz() {
		return clz;
	}

	public void setClz(Clz clz) {
		this.clz = clz;
	}

	public ClzDao getClzDao() {
		return clzDao;
	}

	public void setClzDao(ClzDao clzDao) {
		this.clzDao = clzDao;
	}

	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代表客户选择的文件或者图片,接下来要将图片上传到其他地方
		//img代表源头。要将其写入目的地target
		String destDir="E:/temp/2021/mvc/upload";
		String serverDir="/uploadImages";
		FileUtils.copyFile(img, new File(destDir+"/"+imgFileName));
		//数据库保存的值是/upload/xx.png
		//图片是在E:/temp/2021/mvc/upload/1.png
		//访问:http://localhost:8080/struts/uploadImages/xx.png
		clz.setPic(serverDir+"/"+imgFileName);

		this.clzDao.edit(clz);
		return TOLIST;
	}
	
	

3、struts-sy.xml配置

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

4.映射路径(server.xml)

     <Context docBase="E:/temp/2021/mvc/upload/" path="/uploadImages"/>	

 5.clzlist.jsp修改代码

6.运行结果

①点击上传图片

 ②提交成功

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值