上传文件
-
首先编写
Controller
接口接收文件。@RestController @RequestMapping("/file/") @CrossOrigin public class FileController { @Autowired private FileService fileService; @PostMapping("upload/avatar") public Result uploadAvatar(MultipartFile file){ // 允许上传的文件类型 List<String> type_list = Lists.newArrayList("jpg", "jpeg", "png", "gif"); return Result.ok().data("src",fileService.uploadFile(file,type_list)); } }
-
service
中保存文件。@Service public class FileServiceImpl implements FileService { // 上传文件 @Override public String uploadFile(MultipartFile file, List<String> type) { // 获取文件名称 String originalFilename = file.getOriginalFilename(); // 获取上传文件后缀 String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase(); // 判断文件后缀是否符合返回要求 if (type.contains(fileSuffix)) { // 避免文件类型重复 用UUID+原后缀 // 记得加"." String newFileName = UUID.randomUUID() + "." + fileSuffix; // 获取当前项目路径 String dirPath = System.getProperty("user.dir"); // 拼接文件保存路径 String path = dirPath + File.separator + "upload" + File.separator + "avatar" + File.separator + newFileName; File destFile = new File(path); // 如果文件路径不存在则创建文件夹 if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } try { // 写入文件 file.transferTo(destFile); // 返回相对路径 return "upload/avatar/" + newFileName; } catch (IOException e) { e.printStackTrace(); } } else { throw new EducationException(20001,"文件类型不符合要求。"); } throw new EducationException(20001,"上传失败,未知错误。"); } }