项目目录结构:
项目依赖包:
FileUploadController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| package com.course.controller;
import java.io.File; import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile;
import com.course.util.FileUtil; import com.course.util.RandomUtil;
@Controller @RequestMapping("upload") public class FileUploadController {
@RequestMapping("upload01") public String upload01(MultipartFile testfile, HttpServletRequest httpServletRequest) { System.out.println("upload file = " + testfile);
String contentType = testfile.getContentType(); String formInputElementName = testfile.getName(); String originalFilename = testfile.getOriginalFilename(); long fileSize = testfile.getSize(); System.out.println("contentType = " + contentType); System.out.println("formInputElementName = " + formInputElementName); System.out.println("originalFilename = " + originalFilename); System.out.println("fileSize = " + fileSize + " bytes"); String fileDir = httpServletRequest.getServletContext().getRealPath("/upload"); System.out.println("fileDir = " + fileDir); File upFile = new File(fileDir, originalFilename); try { testfile.transferTo(upFile); } catch (IOException e) { e.printStackTrace(); }
return "success"; } @RequestMapping("upload02") public String upload02(MultipartFile[] testfile, HttpServletRequest httpServletRequest) { if (testfile != null && testfile.length > 0) { for (int i = 0; i < testfile.length; i++) { String originalFilename = testfile[i].getOriginalFilename(); String fileDir = httpServletRequest.getServletContext().getRealPath("/upload"); File upFile = new File(fileDir, originalFilename); try { testfile[i].transferTo(upFile); } catch (IOException e) { e.printStackTrace(); } } } return "success"; }
@RequestMapping("upload03") public String upload03(MultipartFile testfile, HttpServletRequest httpServletRequest) { String originalFilename = testfile.getOriginalFilename(); String randomFileName = RandomUtil.getRandomFileName1(originalFilename); String fileDir = httpServletRequest.getServletContext().getRealPath("/upload"); File upFile = new File(fileDir, randomFileName); try { testfile.transferTo(upFile); } catch (IOException e) { e.printStackTrace(); } return "success"; }
@RequestMapping("upload04") public String upload04(MultipartFile testfile, HttpServletRequest httpServletRequest) { String originalFilename = testfile.getOriginalFilename(); String randomFileName = RandomUtil.getRandomFileName1(originalFilename); String fileDir = httpServletRequest.getServletContext().getRealPath("/upload"); String uploadDirByDate = FileUtil.makeUploadDirByDate(fileDir); File upFile = new File(uploadDirByDate, randomFileName); try { testfile.transferTo(upFile); } catch (IOException e) { e.printStackTrace(); } return "success"; } }
|
RandomUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| package com.course.util;
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.UUID;
public class RandomUtil {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); private static Random random = new Random(); public static String getRandomFileName1(String originalFileName) { int lastDotIndex = originalFileName.lastIndexOf("."); String suffix = originalFileName.substring(lastDotIndex, originalFileName.length()); String timeStr = simpleDateFormat.format(new Date()); int randomNum = random.nextInt(9000) + 1000; String fileName = timeStr + randomNum + suffix; System.out.println("fileName = " + fileName); return fileName; } public static String getRandomFileName2(String originalFileName) { int lastDotIndex = originalFileName.lastIndexOf("."); String suffix = originalFileName.substring(lastDotIndex, originalFileName.length()); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String fileName = uuid + suffix; System.out.println("fileName = " + fileName); return fileName; } public static String getRandomFileName3(String originalFileName) { int lastDotIndex = originalFileName.lastIndexOf("."); String suffix = originalFileName.substring(lastDotIndex, originalFileName.length()); String time1 = String.valueOf(System.currentTimeMillis()); System.out.println("time1 = " + time1); String time2 = String.valueOf(new Date().getTime()); System.out.println("time2 = " + time2); String randomNum = String.valueOf(random.nextInt(9000) + 1000); System.out.println("randomNum = " + randomNum); String fileName = time1 + randomNum + suffix; System.out.println("fileName = " + fileName);
return fileName; }
}
|
FileUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.course.util;
import java.io.File; import java.text.SimpleDateFormat; import java.util.Date;
public class FileUtil {
public static String makeUploadDirByDate(String uploadDir) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); Date date = new Date(); String dateStr = simpleDateFormat.format(date); String year = dateStr.substring(0, 4); String month = dateStr.substring(4, 6); String day = dateStr.substring(6, 8); String dateDir = year + "/" + month + "/" + day; File uploadDirByDate = new File(uploadDir, dateDir); if (!uploadDirByDate.exists()) { uploadDirByDate.mkdirs(); } String uploadPath = uploadDirByDate.getAbsolutePath(); return uploadPath; } }
|
log4j.properties
1 2 3 4 5 6 7 8
| log4j.rootLogger=INFO, stdout
log4j.logger.org.mybatis.example.BlogMapper=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
|
springmvc.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.course.controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="uploadTempDir" value="/upload/temp"></property> <property name="maxUploadSize" value="20971520"></property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
|
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>01_springmvc_hello</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name>
<servlet-name>springmvc</servlet-name> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
|
index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body>
<h2>1.上传单个文件(不修改文件名)</h2> <form action="upload/upload01.do" method="post" enctype="multipart/form-data"> 选择文件: <input type="file" name="testfile"> <br/> <input type="submit" value="提交"> </form> <h2>2.上传多个文件(不修改文件名)</h2> <form action="upload/upload02.do" method="post" enctype="multipart/form-data"> 选择文件1: <input type="file" name="testfile"> <br/> 选择文件2: <input type="file" name="testfile"> <br/> 选择文件3: <input type="file" name="testfile"> <br/> <input type="submit" value="提交"> </form> <h2>3.上传单个文件(修改文件名)</h2> <form action="upload/upload03.do" method="post" enctype="multipart/form-data"> 选择文件: <input type="file" name="testfile"> <br/> <input type="submit" value="提交"> </form> <h2>4.上传单个文件(修改文件名,并且分文件夹管理)</h2> <form action="upload/upload04.do" method="post" enctype="multipart/form-data"> 选择文件: <input type="file" name="testfile"> <br/> <input type="submit" value="提交"> </form> </body> </html>
|
success.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <p>上传成功!</p> </body> </html>
|
浏览器访问: http://localhost:8080/08_springmvc_fileupload/index.jsp