1、添加依赖,如果使用maven的话
<!--apache文件上传依赖包-->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-
fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
而如果没用maven则需要自己去下载个jar包
2、在springmvc.xml当中注册文件上传解析器
<!--文件上传解析器
id必须为multipartResolver
原因是源代码中写死为这个名字
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--定义最大上传大小,总的,单位为bytes-->
<property name="maxUploadSize" value="1048576"></property>
<!--指定上传的编码-->
<property name="defaultEncoding" value="UTF-8"></property>
<!--单个文件最大上传大小-->
<property name="maxUploadSizePerFile" value="2000000"/>
</bean>
3、上传页面如图所示
<%--
Created by IntelliJ IDEA.
User: T
Date: 2019/6/25
Time: 17:21
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>
<%--记得添加一个enctype="multipart/form-data",否则后台无法解析 --%>
<form action="${ctx}/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>
</html>
4、上传处理的Controller页面
package com.xs.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;
@Controller
@RequestMapping("/file")
public class FileController {
//定义上传路径,E盘根目录
private static String uploadPath = "E:" + File.separator;
//入参就可以代表上传文件
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile multipartFile, Model model) {
//1、传到哪里去 2、我传什么东西 3、传的细节
//1、判断
if (multipartFile != null && !multipartFile.isEmpty()) {
//不空才传
//2、获取原始文件名
String originalFilename = multipartFile.getOriginalFilename();
//3、 先截取原文件的文件名前缀,不带后缀
String fileNamePrefix=originalFilename.substring(0,originalFilename.lastIndexOf("."));
//4、加工处理文件名,将原文件+时间戳
String newFileNamePrefix=fileNamePrefix+new Date().getTime();
//5、得到新文件名
String newFileName=newFileNamePrefix+originalFilename.substring(originalFilename.lastIndexOf("."));
//6、构建文件对象
File file=new File(uploadPath+newFileName);
//7、上传
try {
multipartFile.transferTo(file);
model.addAttribute("fileName",newFileName);
}catch (IOException e){
e.printStackTrace();
}
}
return "uploadSuc";
}
}
5、最后大功告成