SpringBoot进行文件上传下载的处理方式

文件上传

针对前端form-data形式提交的文件可以直接使用spring的web包下的MultipartFile类进行接收:

@PostMapping("/upload")
    public R uploadImg(MultipartFile file){
        return R.success();
    }

准存到本地有两个方法,一个是使用MultipartFiletransferTo()方法,需注意这个方法入参写入的目的地址要使用绝对路径;二是获取输入流通过传统的方式写入。

文件下载

这里采用的下载方式为直接向浏览器输出文件流的方式:

@GetMapping("/download")
    public void downloadImg(@RequestParam(value = "name", required = false) @NotBlank(message = "文件名称为空") String name,
                            HttpServletResponse response){
        try {
            commonService.doDownload(name, response.getOutputStream());
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuijiException(ExceptionCodeEnum.FILE_DOWNLOAD_FAIL);
        }
    }

这个controller方法为使用文件名称下载对应文件,业务层下载逻辑为:

public void doDownload(String name, OutputStream outputStream){
        String destFilePath = System.getProperty("user.dir") + "\\img";
        File file = new File(destFilePath + "\\" + name);
        try {
            FileUtils.copyFile(file, outputStream);
        } catch (IOException e) {
            log.error(e.getMessage());
            log.error("文件下载失败");
            throw new RuijiException(ExceptionCodeEnum.FILE_DOWNLOAD_FAIL);
        }
    }

这里使用commons-io包的FileUtils工具类完成的文件流输出,直接输出到HttpservletResponse的输出流即可。

你可能感兴趣的:(springboot)