前言:文件上传几乎是不可缺少的功能点,必学知识点!!
一、介绍按照文件上传后保存的位置可以分为三种。
①该项目下的文件夹中 ②存到电脑磁盘中 ③存到云服务器中,也能是文件服务器(最常用) ④二进制形式保存在数据库中(最安全)这不是有四点吗,为什么是三种呢?其实②和③是可以规划为一种的。我们在开发时,自己
电脑启动服务运行项目,然后测试文件上传功能,下载到本地磁盘中。在这里,可以将我们
电脑理解成即是运行项目的服务器,也是文件服务器。如果多一台电脑,那台电脑作为文件
件服务器,我们仅仅在上传时请求文件服务器即可,文件服务器帮我们下载。
使用的服务器:ECS云服务器(推荐:阿里云,腾讯云,西部数码)
二、使用(Struts2) 1、upload.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
文件上传界面
注意:表单是多功能表单 enctype="multipart/form-data"
2、ClazzActionpackage com.zwf.web; import java.util.HashMap; import java.util.List; import java.util.Map; import com.zwf.Dao.ClazzDao; import com.zwf.Po.Clazz; import com.zwf.util.baseAction; import com.zwf.util.PageBean; import com.zwf.util.ResponseUtil; public class ClazzAction extends baseAction3、Struts-sy.xml{ 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; } public String preUpload() throws Exception { this.result=this.cd.list(clz, null).get(0); this.req.setAttribute("result", result); return "upload"; } public String upload() throws Exception { //img代表客户选择的文件(图片),接下来要将图片上传到其他地方 //img代表了源头,要将其写入目的地destDir 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; } }
/clzList.jsp /clzEdit.jsp /clz_list /upload.jsp



