前言:先思考一下文件上传到哪里?---------服务器
1.文件上传的前提条件
①在表单中
②method的提交方式是post
③上传的文件编码不能是默认编码,要为二进制编(enctype="multipart/form-date")
④input的类型是File类型 并且输入框要有name属性
2.文件上传的原理
客户端发送请求到达前端控制器,--》文件解析器---》返回给前端控制器--》Controller中文件上传的方法。
注意:需要将表单中的数据存储到数据库,不能直接存图片,需要存储图片的路径
3.普通本地上传。
3.1 配置文件上传的解析器
<!--文件上传的解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxInMemorySize" value="104857600" /> </bean>
3.2 文件上传的依赖
<!--①文件上传的依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
3.3 Jsp前端代码
<%-- Created by IntelliJ IDEA. User: 24284 Date: 2021/12/7 Time: 15:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="${pageContext.request.contextPath}/a" method="post" enctype="multipart/form-data"> 头像:<input type="file" name="myfile"><br> 姓名:<input type="text" name="name"><br> 性别:<input type="text" name="sex"><br> <input type="submit" value="提交"> </form> </body> </html>
3.4 controller 控制层代码
/** * @author 24284 * @version 1.0 * Create by 2021/12/7 15:05 */ @Controller public class UploadController1 { @RequestMapping("/a") public String uoload01(MultipartFile myfile, HttpServletRequest request, User user){ HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); String path = servletContext.getRealPath("/upload"); File file = new File(path); if(!file.exists()){ file.mkdir(); } String filename = myfile.getOriginalFilename(); filename=new Date().getTime()+filename; File target = new File(path + "/"+ filename); try { myfile.transferTo(target); } catch (Exception e) { e.printStackTrace(); } String headImg="http://localhost:8080/SpringMvc05/upload/"+filename; request.setAttribute("imgsrc",headImg); user.setHeadImg(headImg); return "success"; } }
3.5 看是否在tomcat的部署的工程目录下有选择的图片,若是有就代表本地上传成功
4. AJAX的普通本地上传
4.1 配置文件上传的解析器
<!--文件上传的解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxInMemorySize" value="104857600" /> </bean>
4.2 文件上传的依赖
<!--①文件上传的依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
4.3 Jsp前端界面代码
<%-- Created by IntelliJ IDEA. User: 24284 Date: 2021/12/7 Time: 16:10 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"> </script> </head> <body> <form id="userForm"> 头像:<input type="file" name="myfile"><br> 姓名:<input type="text" name="name"><br> 性别:<input type="text" name="sex"><br> <input type="button" id="btn" value="提交"/> </form> <img id="headImg"> <script> $("#btn").click(function (){ let formData = new FormData(document.getElementById("userForm")); $.ajax({ url:"${pageContext.request.contextPath}/b", type:"post", processData: false, contentType:false, data:formData, success:function (result){ if(result.code===2000){ $("#headImg").attr("src",result.imgsrc); } }, dataType:"json" }) }) </script> </body> </html>
4.4 Controller 控制代码
import java.io.File; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author 24284 * @version 1.0 * Create by 2021/12/7 16:20 */ @Controller public class uploadController2 { @RequestMapping("/b") @ResponseBody public Map<String,Object> upload2(MultipartFile myfile, HttpServletRequest request, User user ){ Map<String,Object>map=new HashMap<String, Object>(); HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); String path = servletContext.getRealPath("upload"); File file = new File(path); if(!file.exists()){ file.mkdirs(); } String filename = myfile.getOriginalFilename(); filename = new Date().getTime() + filename; File target = new File(path + "/" + filename); try { myfile.transferTo(target); map.put("code",2000); map.put("msg","上传成功"); map.put("imgsrc","http://localhost:8080/SpringMvc05/upload/"+filename); return map; } catch (IOException e) { e.printStackTrace(); } map.put("code",5000); map.put("msg","上传失败"); return map; } }
同理在tomcat的服务部署目录下看能否找到上传的文件