springboot文件上传 MultipartFile file,源自SpringMVC
(1)静态页面放在static目录下
(2)直接访问:localhost:8080/upload.html
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="himg"/><p/>
姓名:<input type="text" name="name"/><p/>
<input type="submit" value="上传"/>
</form>
(3)控制器UploadController 处理业务
@RestController
public class UploadController {
//绝对路径
private static final String filePath = "D:\\javalesson\\demoboot1\\src\\main\\resources\\static\\images\\";
@PostMapping("/upload")
public JsonData upload(@RequestParam("himg") MultipartFile file, HttpServletRequest request) {
//图片大小进行判断
// file.getSize()
//图片是否为空
if (!file.isEmpty()) {
//获取文件名
String name = request.getParameter("name");
System.out.println(name);
// 获取文件名
String fileName = file.getOriginalFilename();
System.out.println("上传的文件名为:" + fileName);
// 获取后缀名 如:jpg,png
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println(suffixName);
//拼接路径
File destPath = new File(filePath + fileName);
System.out.println(destPath);
try {
//文件保存
file.transferTo(destPath);
return new JsonData(0, "上传成功", fileName);
} catch (IOException e) {
e.printStackTrace();
}
return new JsonData(-1, "上传失败!", fileName);
}
return new JsonData(-1, "上传失败!", null);
}
}
(4)运行 http://localhost:8080/upload.html
查看目录路径:
http://localhost:8080/images/girl.png