美文网首页
Spring Boot 06 -- 文件上传

Spring Boot 06 -- 文件上传

作者: 半碗鱼汤 | 来源:发表于2019-08-20 21:10 被阅读0次

    一、说明

    给工程添加一个文件上传接口

    二、controller

        @Autowired
        private ITestService testService;
    
        @PostMapping("/upload")
        @ResponseBody
        public String upload(@RequestParam(value = "file") MultipartFile file) {
    
            if (file.isEmpty()) {
                return "上传失败,请选择文件";
            }
    
            return testService.upload(file);
        }
    

    三、service

        String upload(MultipartFile file);
    

    四、service impl

        private static final Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);
    
        @Value("${file.upload.path}")
        private String uploadPath;
    
        @Override
        public String upload(MultipartFile file) {
    
            String fileName = file.getOriginalFilename();
            String filePath = uploadPath;
    
            File dest = new File(filePath);
            // 判断文件夹是否存在
            if (dest.isDirectory()) {
                logger.info("文件夹存在");
            } else {
                logger.info("文件夹不存在,正在创建...");
                dest.mkdirs();
                logger.info("文件夹创建成功");
            }
    
            dest = new File(filePath + fileName);
            //判断文件是否存在
            if (dest.exists()) {
                logger.info("文件已存在,覆盖之...");
            }
    
            try {
    
                file.transferTo(dest);
    
                logger.info("上传成功");
                logger.info("上传文件路径为:" + filePath + fileName);
                return filePath + fileName;
    
            } catch (IOException e) {
                logger.error(e.toString(), e);
            }
            return "上传失败!";
        }
    

    五、完成

    相关文章

      网友评论

          本文标题:Spring Boot 06 -- 文件上传

          本文链接:https://www.haomeiwen.com/subject/kxvmsctx.html