首先有个上传文件的工具类
/**
* 文件上传
* @param file
* @param filePath
* @param fileName
* @throws Exception
*/
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+File.separator+fileName);
out.write(file);
out.flush();
out.close();
}
2. 配置真实路径与虚拟路径的映射关系
public class TestApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } @Value("${upload.filePath}") private String filePath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler("/"); registry.addResourceHandler("/images/**").addResourceLocations("file:"+filePath); super.addResourceHandlers(registry); } }
3. 上传的主要方法实现
@PostMapping("/test/common/uploadFile") public String uploadFile( @RequestParam("file") MultipartFile file, HttpServletRequest request) { try { //定义相对路径 String relativePath = File.separator+DateUtil.getToday()+File.separator; String path = filePath + relativePath; String fileName = file.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replaceAll("-",""); String suffix = fileName.substring(fileName.lastIndexOf(".")); //随机生成新的文件名,防止文件名冲突或者中文乱码问题 String newFileName = uuid+suffix; //调用上传方法将文件上传到物理路径下 FileUtil.uploadFile(file.getBytes(),path,newFileName); //可选:将图片路径存储起来为了定期清理图片(可以存储到非关系型数据库中,如mongodb) PicturePathDTO dto = new PicturePathDTO(); dto.setPath(images+relativePath+newFileName); dto.setCreateTime(new Date()); picturePathDao.save(dto); //返回虚拟路径 return (images+relativePath+newFileName); } catch (Exception e) { e.printStackTrace(); } return null; }