天天看点

Springboot文件上传下载文件上传

在web开发中,文件上传下载是很常用的功能,spring也集成了相应的工具类.

本文用代码简单示例文件上传下载功能.

文件上传下载

  • 文件上传
    • 文件下载

文件上传

公共方法:

//此处只校验文件不为空.
    protected String upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        File picSaveP = new File(savePath);
        if (!picSaveP.exists()) {
            picSaveP.mkdirs();
        }
        String random = UUID.randomUUID().toString();
        String fileNameStr =random + fileName;
        File targetFile = new File(picSaveP, fileNameStr);
        FileCopyUtils.copy(file.getBytes(),targetFile);
       //file.transferTo(targetFile);
       return fileNameStr;
    }
           

1.1 savePath为相对路径的地址,写在配置文件中,然后在代码中使用@value注解引用.

shell:
  savePath: /opt/image/
  
 @Value("${shell.savePath}")
    public String savePath;
           

1.2如果使用file.transferTo(targetFile)方法,不能使用相对路径,使用相对路径会报错,使用FileCopyUtils方法,为spring的工具类,保存文件的地址和项目在同一个盘符.

测试: controller层 调用此upload方法.

//上传文件,controller
    @PostMapping(value = "/uploadThumbnail")
    public String uploadThumbnail(MultipartFile file) throws IOException   {
        return upload(file);
    }
           

postman测试:

Springboot文件上传下载文件上传

返回结果为一个相对路径的图片名称.因为我的项目在D盘,所以最后生成的图片也会存放在D盘.

Springboot文件上传下载文件上传

文件下载

公共方法:

/**
     * 文件下载
     * @param fileName
     * @param inputStream
     * @return
     * @throws IOException
     */
    protected ResponseEntity<InputStreamResource> exportSource(String fileName, InputStream inputStream)
        throws IOException {
        log.info("fileName:{}", fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CACHE_CONTROL, "NO-cache, NO-store, must-revalidate");
        headers.add(HttpHeaders.PRAGMA, "NO-cache");
        headers.add(HttpHeaders.EXPIRES, "0");
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
        return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(new InputStreamResource(inputStream));
    }
           

测试: controller层. 调用exportSource方法.

//下载图片,url为图片的名称.
    @GetMapping(value = "/getThumbnails")
    public ResponseEntity<InputStreamResource> getThumbnails(String url) throws IOException {
        if (StringUtils.isEmpty(url)){throw new UniqueException("url不能为空");}
        //savePath和文件上传的路径一样.
         File file = new File(savePath+url);
           if(!file.exists() && !file.isFile()){
            {throw new UniqueException("文件不存在");}
        }
        InputStream in = new FileInputStream(file);
        return exportSource(file.getName(), in);
    }
           

postman示例:点击send and Download是请求和下载文件.

Springboot文件上传下载文件上传
Springboot文件上传下载文件上传