一:文件上传的三种方式
1、上传到tomcat服务器
2、上传到指定文件目录,添加服务器与真实目录的映射关系
3、在数据库表中建立二进制字段,将图片存储到数据库(其安全性比第二种高)
二:上传展示
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、运行结果
6.1、点击图片上传
6.2、图片展示