SpringBoot进阶之文件上传(单文件上传/多文件上传)

来源:互联网 发布:java代理模式的好处 编辑:程序博客网 时间:2024/05/01 08:26

1.单文件上传

    private String uploadPath="D:\\tomcat\\apache-tomcat-7.0.81-windows-x64\\apache-tomcat-7.0.81\\webapps\\img\\";    private String URL="http://127.0.0.1:8880/img/";    /**     * 单个文件上传   文件上传成功后返回文件的访问路径     * @param file     * @return     */    @ResponseBody    @RequestMapping(value = "/upload",method = RequestMethod.POST)    public Msg upload(@RequestParam("file")MultipartFile file) {        if(!file.isEmpty()) {            File fil=new File(uploadPath+file.getOriginalFilename());            try {                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fil));                out.write(file.getBytes());                out.flush();                out.close();            } catch (FileNotFoundException e) {                e.printStackTrace();                return ResultUtil.error(200, "文件上传失败{}" + e.getMessage());            } catch (IOException e) {                e.printStackTrace();                return ResultUtil.error(200, "文件上传失败{}" + e.getMessage());            }            return ResultUtil.success(URL+fil.getName());       //返回上传文件的访问路径   getAbsolutePath()返回文件上传的绝对路径        }else {            return ResultUtil.error(201, "文件上传失败,文件为空");        }    }

postman请求效果图:



2.多文件上传

    private String uploadPath="D:\\tomcat\\apache-tomcat-7.0.81-windows-x64\\apache-tomcat-7.0.81\\webapps\\img\\";    private String URL="http://127.0.0.1:8880/img/";    /**     * 多文件上传 并返回各个文件的访问路径     * @param files     * @return     */    @ResponseBody    @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)    public Msg batchUpload(@RequestParam("files")MultipartFile[] files) {        String uploadedFileName = Arrays.stream(files).map(x -> x.getOriginalFilename())                .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));        if (StringUtils.isEmpty(uploadedFileName)) {            return ResultUtil.error(201,"文件上传失败,文件为空");        }        List<String> path=new ArrayList<>();        try {           path=  saveUploadedFiles(Arrays.asList(files));        } catch (IOException e) {            return ResultUtil.error(201,"文件上传异常"+e.getMessage());        }        return ResultUtil.success(path);    }    private  List<String> saveUploadedFiles(List<MultipartFile> files) throws IOException {       List<String> paths=new ArrayList<>();        for (MultipartFile file : files) {            if (file.isEmpty()) {                continue;            }            byte[] bytes = file.getBytes();            Path path = Paths.get(uploadPath + file.getOriginalFilename());            paths.add(URL + file.getOriginalFilename());            //保存上传文件的访问路径            Files.write(path, bytes);        }      return paths;    }


请求效果图:




附:

Java 8 中的 Stream API 详解:Stream详解


原创粉丝点击