一、文件上传的三种方式
1、上传到Tomcat服务器
自己的电脑项目在哪图片就在哪
云服务器:是没有CDEF盘的,只有根目录
2、上传到指定文件目录(用的比较多)
添加服务器与真实目录的映射关系,从而解耦上传文件与Tomcat的关系文件服务器和web服务器通常是一个,但是文件目录与Tomcat目录肯定不是同一个
3、在数据库表中建立二进制段,将图片存储到数据库,安全性比第二种高
服务器:ESC服务器(阿里云、腾讯云、西部数码云)
注意事项
1、上传文件界面:entype="multipart/form-data" type="file"
2、Struts必须按照指定的格式去接收参数变量
二、文件上传代码(第二种)
CLzAction
package com.lxy.crud.web;
import java.io.File;
import org.apache.commons.io.FileUtils;
import com.lxy.crud.dao.ClzDao;
import com.lxy.crud.entity.Clz;
import com.lxy.crud.util.BaseAction;
import com.lxy.crud.util.PageBean;
public class ClzAction extends BaseAction<Clz> {
/**
* 按照指定的格式曲接受参数变量
* 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;
}
/**
* 跳转到文件上传界面
* @return
* @throws Exception
*/
public String preUpload() throws Exception {
this.result=this.clzDao.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.clzDao.edit(clz);
return TOLIST;
}
}
Struts-sy.xml配置
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"><br>
<input type="submit">
</form>
</body>
</html>
<td><img alt="" src="${b.pic}" style="width: 50px;height: 70px;"></td>
<td>
<a href="${pageContext.request.contextPath}/sy/clz_toEdit.action?cid=${b.cid}">修改</a>
<a href="${pageContext.request.contextPath}/sy/clz_del.action?cid=${b.cid}">删除</a>
<a href="${pageContext.request.contextPath}/sy/clz_preUpload.action?cid=${b.cid}">上传图片</a>
</td>
运行结果