使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM