上传文件(SpringBoot Mybatis-Plus)


Controller

   /**
     * 文件上传
     */
    @PostMapping(value = "/uploadFile")
    @ResponseBody
    public HttpResult uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        sysSubjectService.uploadSubjectMould(multipartFile);
        return HttpResult.ok("上传完成");
    }

Service

 @Override
    public Boolean uploadSubjectMould(MultipartFile multipartFile) {
        FileIOUtil fileIOUtil = new FileIOUtil();
        Boolean flag = fileIOUtil.uploadFile(multipartFile);
        return flag;
    }

FileIOUtil

import org.apache.tomcat.util.http.fileupload.util.Streams;

public class FileIOUtil {
        public Boolean uploadFile(MultipartFile multipartFile) {
            //设置文件名以及路径
            String fileName = new String(multipartFile.getOriginalFilename()
 .substring(multipartFile.getOriginalFilename().indexOf(".")));
            String filePath = "D:\\file" + File.separator + fileName;

            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                if (multipartFile != null) {
                    try {
                        //以原来的名称命名,覆盖掉旧的
                        Streams.copy(multipartFile.getInputStream(), new FileOutputStream(filePath), true);
                        //或者下面的
                        // Path path = Paths.get(storagePath);
                        //Files.write(path,multipartFile.getBytes());
                    } catch (IOException e) {
                        ExceptionUtils.getFullStackTrace(e);
                    }
                }
            } catch (Exception e) {
                return false;
            }
            return true;
        }
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM