/**上傳文件 * @param file 文件 * @param filePath 上傳文件路徑,不包含文件名 * @param fileName 新的文件名 * @return 返回一個路徑名 * @throws Exception */ public static String uploadFile(MultipartFile file, String filePath, String fileName) throws Exception { //原文件名 String filename = file.getOriginalFilename(); //獲取文件后綴名 String suffix = filename.substring(filename.lastIndexOf(".")); //判斷目錄是否為空,若為空新建目錄 File targetFile = new File(filePath); if(!targetFile.exists()){ targetFile.mkdirs(); } //上傳文件路徑 String path = filePath+"/"+fileName+suffix; //上傳 FileOutputStream out = new FileOutputStream(path); out.write(file.getBytes()); out.flush(); out.close(); return path; }
調用:
@ApiOperation("上傳文件") @PostMapping(value = "/uploadFile", consumes = "multipart/*",headers = "content-type=multipart/form-data") @ResponseBody public void uploadFile( @RequestParam MultipartFile file) throws Exception { uploadFile(file,"G:/pic","123"); try { } catch (Exception e) { e.printStackTrace(); } }