标签:com mon png att resolve void map 解析 文件的
2.网页。
表单必须是post提交,编码必须是multipart/form-data 文件上传文本框必须起名。
1 <form action="addstudent" method="post" enctype="multipart/form-data"> 2 姓名:<input type="text" name="name"/> 3 年龄:<input type="text" name="age"/> 4 头像:<input type="file" name="photo"/> <!-- 这里的name必须和controller的()里面的相同 --> 5 <input type="submit" value="上传"/> 6 </form>
1 <!-- 配置文件上传的解析器 --> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 <!-- name:指上传文件的大小 value:指上传文件设定的值 --> 4 <property name="maxUploadSize" value="999999999"></property> 5 </bean>
1 package com.zhiyou100.wc.controllter; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 6 import javax.servlet.http.HttpServletRequest; 7 8 import org.apache.commons.io.FileUtils; 9 import org.springframework.stereotype.Controller; 10 import org.springframework.web.bind.annotation.RequestMapping; 11 import org.springframework.web.multipart.MultipartFile; 12 13 @Controller 14 public class UploadController { 15 16 @RequestMapping("upload") //HttpServletRequest:作用是为了获取上传文件的路径 17 public String upload(MultipartFile myfile,HttpServletRequest request){//MultipartFile myfile:把你上传的文件封装到MultipartFile中 18 //1.一般情况下上传到服务器的目录下,获取网站根目录 19 //获取文件上传真实保存的路径 20 String path=request.getServletContext().getRealPath("/upload"); 21 22 //2.创建一个文件对象 23 File file =new File(path); 24 if(!file.exists()) {//该路径不存在 25 file.mkdirs(); 26 } 27 //3.获取文件名 用:getOriginalFilename 28 String name= myfile.getOriginalFilename(); 29 30 File targetFile=new File(path+"/"+name); 31 32 33 34 System.out.println(name); 35 return "redirect:login.jsp"; 36 37 } 38 39 40 }
1.MyInterceptor.java
1 package com.zhiyou100.wc.interceptor; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.web.servlet.HandlerInterceptor; 7 import org.springframework.web.servlet.ModelAndView; 8 9 public class MyInterceptor implements HandlerInterceptor{ 10 11 @Override 12 public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) 13 throws Exception { 14 15 } 16 17 @Override 18 public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) 19 throws Exception { 20 21 } 22 23 @Override 24 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { 25 Object name= request.getSession().getAttribute("name"); 26 if(name!=null) { 27 return true; 28 }else { 29 response.sendRedirect("login.jsp"); 30 return false; 31 } 32 33 } 34 35 }
标签:com mon png att resolve void map 解析 文件的
原文地址:https://www.cnblogs.com/banzhuanlaowang/p/11462631.html