使用CommonsMultipartFile上传文件

控制层

    使用CommonsMultipartFile接收

    

        @RequestMapping(method = RequestMethod.POST)
            public Result   addFile(@RequestParam("file") CommonsMultipartFile file)throws IOException{
                Attach resultData = attachService.saveFile(file).getResultData();
                return ResultUtil.buildSuccess(resultData);
            }

service

  

 @Override
        public Result<Attach> saveFile(CommonsMultipartFile file)   {
            Attach attach = null;
                //根据系统时间插入
            long filetime = System.currentTimeMillis();
            Instant instant = Instant.ofEpochMilli(filetime);
            String format = DateUtil.format(Date.from(instant), YT_DYEART);
            try {
                Attach  ar=new Attach();
                //所在文件夹
                String path="/upload/"+format+"/";
                //文件全路径
                String filte=path+filetime+file.getOriginalFilename();

                File newFile=new File(filte);
                if(!newFile.exists()){
                    newFile.mkdirs();
                }

                //原文件名
                String orgName = file.getOriginalFilename();
                //修改后的文件名
                String name = filetime + file.getOriginalFilename();
                //附件大小
                long size = file.getFileItem().getSize();

                //后缀
                String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") );
                //拷贝   spring封装方法  相当于上传
                file.transferTo(newFile);

                } catch (IOException e) {
                  logger.error("AttachServiceImpl.saveInsertAttach", e);
                  return null;
            }


            return ResultUtil.buildSuccess(attach);
        }

欢迎加入Java开发群 716818594

原文地址:https://www.cnblogs.com/liaohongbin/p/7904536.html