springboot上传文件与回显
资源映射路径配置:
package com.dzqc.yx.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebAppPhotoConfigurer implements WebMvcConfigurer {
@Value("${message.photo_dir}")
private String photo_dir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.err.println(photo_dir);
registry.addResourceHandler("/photo/**").addResourceLocations("file:"+photo_dir);
}
}
用户上传的图片可以在/photo/**路径下访问
磁盘路径地址在.yml配置文件中设置:
message:
md5-key: yx
photo_dir: D:/photo/
上传文件的控制器
@RequestMapping("/binding3")
@ResponseBody
public AjaxResult binding3(HttpSession session,
@RequestParam(value="file",required = true) MultipartFile file){
if(file.isEmpty()){
return AjaxResult.fail("请选择文件");
}
BufferedImage bi = null;
try {
bi = ImageIO.read(file.getInputStream());
if(bi==null){
return AjaxResult.fail("您上传的不是图片格式");
}
} catch (IOException e) {
e.printStackTrace();
return AjaxResult.fail("您上传的不是图片格式");
}
File path = new File(photo_dir);
if(!path.exists()) {
path = new File("");
}
String fileName=file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
File f=new File(path.getAbsolutePath(), UUID.randomUUID().toString()+suffix);
try {
file.transferTo(f);
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.fail("文件保存异常");
}
return AjaxResult.success("上传成功:"+f.getName());
}
文件存放在D:/photo/目录下

