/** * 文件上傳 * @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(); }
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. 上傳的主要方法實現mongodb
@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; }