1、本地上传
新建springboot项目,引入Thymeleaf、web相关依赖:
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-thymeleaf
在项目resource目录下新建templates文件夹并创建上传文件页面upload.html:
文件上传选择文件:
创建success.html页面:
上传成功再创建一个error.html页面
上传失败新建uploadController
@Controller
@RequestMapping("/")
public class UploadController {
@Autowired
private UploadService uploadService;
@GetMapping("/upload")
public String to_upload(){
return "upload";
}
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request, Model model){
if (file!=null){
Map map=uploadService.localUpload(file);
model.addAllAttributes(map);
return "success";
}
model.addAttribute("fileName",file.getOriginalFilename());
model.addAttribute("msg","参数错误!");
return "error";
}
}
service
public interface UploadService {
Map localUpload(MultipartFile file);
}
service实现类
@Service
public class UploadServiceImpl implements UploadService {
@Override
public Map localUpload(MultipartFile file) {
Map resultMap=new HashMap<>();
try {
//原文件名加上时间戳作为上传后保存的文件名
String fileName=System.currentTimeMillis()+file.getOriginalFilename();
//指定目标文件名,此处将文件保存在项目的resource目录下,也可以保存在本地的其他目录下
String destFileName=System.getProperty("user.dir")
+File.separator+"src"
+File.separator+"main"
+File.separator+"resources"
+File.separator+"upload"
+File.separator+fileName;
//新建目标文件
File destFile = new File(destFileName);
//创建目标文件的存储路径
destFile.getParentFile().mkdirs();
//将前端接收的文件转化为目标文件
file.transferTo(destFile);
//将上传后的文件名和存储路径返回
resultMap.put("fileName",fileName);
resultMap.put("path",destFile);
} catch (IOException e) {
e.printStackTrace();
}
return resultMap;
}
}
在项目的resource目录新建application.yml配置文件,添加配置信息
server:
port: 8899 #端口
spring:
thymeleaf:
prefix: classpath:/templates/ #前端页面文件路径
suffix: .html #前端页面文件后缀名
启动项目,浏览器输入http://localhost:8899/upload
选择一张名为test.jpg的图片后提交