SpringMVC上传文件
1,导入上传文件所需jar包 (若无此jar包,上篇文章的地址可下载)
2,配置spring-config.xml
1 <!-- 支持上传文件 --> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 <!-- 设置上传文件的最大尺寸为5MB --> 4 <property name="maxUploadSize"> 5 <value>5242880</value> 6 </property> 7 </bean>
3,新建上传文件页面 upload.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <!-- action="/项目名/类 Controller 注解映射请求路径..." --> 11 <form action="/erp_App/spingmvc/uploadFile.do" method="post" enctype="multipart/form-data"> 12 选择文件:<input type="file" name="file"/> 13 <input type="submit" value="上传"/> 14 </form> 15 </body> 16 </html>
4,上传成功的页面 success.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 上传成功 11 </body> 12 </html>
5,上传文件的Controller
1 package com.st.test.controller; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.util.Date; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServletRequest; 11 12 import org.springframework.stereotype.Controller; 13 import org.springframework.web.bind.annotation.RequestMapping; 14 import org.springframework.web.bind.annotation.RequestParam; 15 import org.springframework.web.multipart.commons.CommonsMultipartFile; 16 17 @Controller 18 @RequestMapping("/spingmvc") 19 public class UploadFileController { 20 21 @RequestMapping("/uploadFile") 22 public String uploadFile(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request)
throws IOException, ServletException{ 23 24 //打印上传文件名 25 System.out.println("fileName..."+file.getOriginalFilename()); 26 //判断文件上传是否为空 27 //若上传文件不为空 28 if(!file.isEmpty()){ 29 try { 30 //输出流(文件上传保存的路径) 31 FileOutputStream os = new FileOutputStream("D:/"+new Date().getTime()+file.getOriginalFilename()); 32 //输入流 33 InputStream in = file.getInputStream(); 34 //读取文件 35 //定义一个读取文件的变量 36 int b=0; 37 while((b=in.read()) != -1){ 38 os.write(b); 39 } 40 os.flush(); 41 os.close(); 42 in.close(); 43 } catch (FileNotFoundException e) { 44 e.printStackTrace(); 45 } 46 }
//上传成功后跳转的页面 47 return "/test/success.jsp"; 48 } 49 }