一.文件上传( 三种上传方案):
1.该项目下的文件夹中(自己的电脑,项目在哪里,图片就在哪里)
2.存到云服务器中,也能是文件服务器(没有CDEF盘的,只有/根目录,最常用)
3.在数据库表中建立二进制字段,将图片存储到数据库(最安全)
服务器推荐:ECS云服务器(阿里云、腾讯云、西部数码云)
二.使用
第一步:创建upload.jsp(定义多功能表单 enype="multiput/form-data")
<%@ 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>
第二步:ClzAction
/*
* 按照指定的格式去接收参数变量
* 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 getImgContentType() {
return imgContentType;
}
public void setImgContentType(String imgContentType) {
this.imgContentType = imgContentType;
}
public String getImgFileName() {
return imgFileName;
}
public void setImgFileName(String imgFileName) {
this.imgFileName = imgFileName;
}
/**
* 跳转到文件上传界面
* @return
* @throws Exception
*/
public String preUpload() throws Exception {
this.result=this.cd.list(clz, null).get(0);
this.req.setAttribute("result", result);
return "upload";
}
/**
* 文件上传
* @return
* @throws Exception
*/
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));
//将图片加到数据库
//数据库保存的值是:/uploadImages/xx.png
//图片是在:E:/temp/2021/mvc/upload/1.png
//访问:http://localhost:8080/struts/uploadImages/xx.png
clz.setPic(serverDir+"/"+imgFileName);
this.cd.edit(clz);
return TOLIST;
}
第三步:配置struts-sy.xml
<result name="upload">/upload.jsp</result>