1.java代码
package com.hcr.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
public class FileController {
@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
public Object upload(@RequestParam(value = "file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
Map result = new HashMap<>(2);
// 获取项目路径
String currentPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
// 获取文件名
String filename = multipartFile.getOriginalFilename();
// 获取文件的后缀名
String subFilename = filename.substring(filename.lastIndexOf("."));
// 重新命名
filename = UUID.randomUUID() + subFilename;
// 创建文件
File file = new File(currentPath + "/upload/" + filename);
if (!file.exists()) {
File dir = file.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
file.createNewFile();
}
multipartFile.transferTo(file);
result.put("code", "1");
result.put("data", file.getPath());
return result;
}
}
2.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" action="/file/upload" method="post">
文件上传:<input type="file" name="file"/> <br/>
姓名:<input type="text" name="name"/> <br/>
<input type="submit" value="提交">
</form>
</body>
</html>
3.访问html页面
路径:http://localhost:8080/upload_file.html
4.测试结果
5.参考文章链接
小滴课堂
HTML上传文件的多种方式
java中获取类加载路径和项目根路径的5种方法
java创建多级目录以及文件