1.引入commons-fileupload-1.3.1.jar及commons-io-2.2.jar两个包
2.在spring容器中声明multipartResolver
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大允许上传大小5MB -->
<property name="maxUploadSize" value="5242880" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
3.创建UploadController.java类接收上传文件
package com.controller;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
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;
@Controller
public class UploadController {
@RequestMapping("/upload")
//接收前端传过来name为"file"的文件
public String upload(@RequestParam(name="file") MultipartFile file,HttpServletRequest request,Model model) throws IllegalStateException, IOException{
// 判断文件是否为空,空则返回失败页面
if (file.isEmpty()) {
model.addAttribute("error", "请选择需要上传的文件!");
return "error";
}
//获取文件存储路径
String path = request.getSession().getServletContext().getRealPath("upload");
//获取上传文件名字
String filename=file.getOriginalFilename();
//获取上传文件类型
String filetype=file.getContentType();
//获取上传文件大小
Long filesize=file.getSize();
//通过字符串切割方式获取.xx的文件类型
String extName = filename.substring(filename.lastIndexOf("."));
//使用UUID对文件重命名
String newname=UUID.randomUUID().toString()+extName;
// 创建文件实例
File filePath = new File(path, newname);
// 如果文件目录不存在,创建目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
//写入文件
file.transferTo(filePath);
System.out.println("文件上传成功!保存进地址为:"+path+"\\"+newname);
System.out.println("文件类型为:"+filetype);
System.out.println("文件大小为:"+filesize);
return "upload";
}
}
4.新建前端上传页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="upload.go" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit">
</form>
</body>
</html>
5.运行项目测试成功输出文件保存路径、文件类型、文件大小
6.打开文件目录查看,文件已上传至指定目录