项目结构:
创建一个包含web与Thymleaf依赖的springboot项目
二、修改配置文件application.properties
# 上传文件总最大值 spring.servlet.multipart.max-request-size=20MB # 上传单个文件最大值 spring.servlet.multipart.max-file-size=20MB #存储路径 file.upload.dir = f:/test/week02/ #页面路径前后缀 spring.mvc.view.prefix=classpath:/templates/ spring.mvc.view.suffix=.html三、编写代码
1、控制层controller
ImageController
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class ImageController {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageController.class);
@Value("${file.upload.dir}")
private String uploadFilePath;
@GetMapping("/upload")
public String upload() {
return "upload";
}
@ResponseBody
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file){
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
//文件名
String fileName = file.getOriginalFilename();
File dest = new File(uploadFilePath + fileName);
//检测目录是否存在
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
//检测文件是否存在
if(dest.exists()){
return "文件已经存在";
}
try {
file.transferTo(dest);
LOGGER.info("上传成功");
return "上传成功";
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
return "上传失败!";
}
}
2、html页面
上传镜像
四、测试
localhost:8080/upload



