这里以上传图片到tomcat服务器作为例子
1. 导入jar包
2. file.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%
StringBuilder builder = new StringBuilder();
builder.append(request.getScheme()).append("://")
.append(request.getServerName()).append(":")
.append(request.getServerPort())
.append(request.getContextPath())
.append("/");
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=builder.toString()%>">
<meta charset="utf-8">
<title>file</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"><br />
文件:<input type="file" name="userFile"><br />
<input type="submit" value="提交">
</form>
</body>
</html>
注意:
form表单的enctype取值必须是:multipart/form-data
默认为:application/x-www-form-urlencoded
method属性取值必须是Post
3. FileUploadController.java
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String upload(String username, MultipartFile userFile, HttpServletRequest request) throws Exception {
// System.out.println(username);
// 获取原始文件名字
String filename = userFile.getOriginalFilename();
// 得到后缀名
String extendName = filename.substring(filename.lastIndexOf("."));
// 通过UUID产生文件名防止文件名重名
filename = UUID.randomUUID() + extendName;
String path = request.getServletContext().getRealPath("/upload");
// path = D:\java\apache-tomcat-8.5.38\webapps\spring-ann\upload
File file = new File(path);
if (!file.exists()) {
// 创建父级文件夹的同时创建子级文件夹
// 如果是mkdir()则只创建一级目录
file.mkdirs();
}
userFile.transferTo(new File(path, filename));
return "redirect:/index.jsp";
}
}