首先需要导入jar包
1.编写一个上传的测试jsp文件
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="springMVC/upload" enctype="multipart/form-data" method="post"> 11 名称:<input type="text" name="picname" /><br> 12 图片:<input type="file" name="uploadFile"><br> 13 <input type="submit" value="上传" /> 14 </form> 15 16 </body> 17 </html>
2.编写控制器
1 @Controller("helloController") 2 @RequestMapping("springMVC") 3 public class HelloController{ 4 @RequestMapping("/upload") 5 public String uploadPic(String picname,MultipartFile uploadFile,HttpServletRequest request) throws IllegalStateException, IOException { 6 //1.定义文件名 7 String fileName = ""; 8 //1.1获取原始文件名 9 String uploadFileName = uploadFile.getOriginalFilename(); 10 //1.2截取文件扩展名(文件后缀) 11 String extendName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1, uploadFileName.length()); 12 System.out.println(extendName); 13 //1.3把文件加上随机数,防止文件重复 14 String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase(); 15 System.out.println("uuid"+uuid); 16 //1.4判断是否输入了文件名,如果输入了文件名,就需要分割传进来的名字, 17 //将后缀名取出与输入文件名结合...最后和uuid相加成最终名字 18 if(!StringUtils.isEmpty(picname)) { 19 fileName = uuid+"_"+picname+"."+extendName; 20 }else { 21 fileName = uuid+"_"+uploadFileName; 22 } 23 System.out.println(fileName); 24 //2.获取文件路径 25 ServletContext context = request.getServletContext(); 26 String basePath = context.getRealPath("/uploads"); 27 //3.解决同一文件夹中文件过多的问题 28 String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); 29 //4.判断路径是否存在 30 File file = new File(basePath+"/"+datePath); 31 if(!file.exists()) { 32 file.mkdirs(); 33 } 34 //5.使用MulitPart接口中方方法,把上传的文件写到指定位置 35 System.out.println(file.getPath()); 37 uploadFile.transferTo(new File(file,fileName)); 38 return "success";//转发到succcess.jsp页面 39 } 40 41 }
3.配置 解析器 spingMVC.xml文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为5M --> <property name="maxUploadSize">
<value>5242880</value>
</property>
</bean
注意:id值是固定的不能修改.
到此就完成了