实现文件上传文件上传的三种方案:
一:上传到tomcat服务器;
自己的电脑:项目在哪,图片就在哪
云服务器:是没有CDEF盘,只有根目录
二:上传到指定文件目录,添加服务器映射关系;
文件服务器和Web服务器通常是同一个,但是文件目录与tomcat目录肯定不是同一个
三:在数据库表中建立二进制字段,将图片存储到数据库;
安全性高
第一步:新建上传文件的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
文件上传
第二步:web层的搭建
package com.lj.web; import java.io.File; import org.apache.commons.io.FileUtils; import com.lj.dao.ClzDao; import com.lj.entity.Clz; import com.zking.util.baseAction; import com.zking.util.PageBean; public class ClzAction extends baseAction{ private Clz clz=new Clz(); private ClzDao clzDao=new ClzDao(); public String list() throws Exception { PageBean pageBean=new PageBean(); pageBean.setRequest(req); this.result=this.clzDao.list(clz, pageBean); this.req.setAttribute("result", result); this.req.setAttribute("pageBean", pageBean); return LIST; } public String toEdit() throws Exception { int cid = clz.getCid(); if(cid!=0) { this.result=this.clzDao.list(clz,null).get(0); this.req.setAttribute("result", result); } return TOEDIT; } public String add() throws Exception { this.clzDao.add(clz); return TOLIST; } public String del() throws Exception { this.clzDao.del(clz); return TOLIST; } public String edit() throws Exception { this.clzDao.edit(clz); return TOLIST; } @Override public Clz getModel() { // TODO Auto-generated method stub return clz; } 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代表客户选择的文件或图片,接下来要将图片上传到其他地方 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/ //访问:http://localhost:8080/my_struts2/uploadImages/20210925102437.png clz.setPic(serverDir+"/"+imgFileName); this.clzDao.edit(clz); return TOLIST; } }
第三步:配置xml
第四步:为主页面添加方法以及图片上传的按钮
结果展示:



