使用restTemplate上传文件的两种方式(推荐阅读)

使用FileSystemResource实现

代码如下:

// 构建请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("appCode", "platform-device");
        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        // 构建请求体
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        Assert.notNull(fileName,"获取上传的原始文件名不能为空");
        File file = new File(fileName);
        try (OutputStream out = new FileOutputStream(file)) {
            // 输入流和输出流之间的拷贝
            FileCopyUtils.copy(multipartFile.getInputStream(),out);
        } catch (IOException e) {
            log.info("上传的文件转换异常" + e.getMessage());
        }
         //从File句柄创建一个新的FileSystemResource
        FileSystemResource resource = new FileSystemResource(file);
        requestBody.add("upload_file", resource);

        // 发送上传请求
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders);
        ResponseEntity<HashMap> responseEntity = restTemplate.postForEntity("你的文件上传路径",
                requestEntity, HashMap.class);

总结:
使用这种方式的好处就是写起来比较简单,缺点是会在项目根路径下生成一个临时文件,上传成功之后你需要将生成的临时文件删除掉

使用InputStreamResource实现

首先需要重写InputStreamResource,重写的原因是防止多次读取流时报错,所以要重写contentLength方法,以及不想在本地新建临时文件需要重写getFilename方法

public class CommonInputStreamResource extends InputStreamResource {
    private long length;
    private String fileName;

    public CommonInputStreamResource(InputStream inputStream, long length,String fileName) {
        super(inputStream);
        this.length = length;
        this.fileName = fileName;
    }

    /**
     * 覆写父类方法
     * 如果不重写这个方法,并且文件有一定大小,那么服务端会出现异常
     * {@code The multi-part request contained parameter data (excluding uploaded files) that exceeded}
     */
    @Override
    public String getFilename() {
        return fileName;
    }

    /**
     * 覆写父类 contentLength 方法
     * 因为 {@link org.springframework.core.io.AbstractResource#contentLength()}方法会重新读取一遍文件,
     * 而上传文件时,restTemplate 会通过这个方法获取大小。然后当真正需要读取内容的时候,发现已经读完,会报如下错误。
     * <code>
     * java.lang.IllegalStateException: InputStream has already been read - do not use InputStreamResource if a stream needs to be read multiple times
     * at org.springframework.core.io.InputStreamResource.getInputStream(InputStreamResource.java:96)
     * </code>
     * <p>
     * ref:com.amazonaws.services.s3.model.S3ObjectInputStream#available()
     */
    @Override
    public long contentLength() {
        long estimate = length;
        return estimate == 0 ? 1 : estimate;
    }

    public void setLength(long length) {
        this.length = length;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

具体实现:

// 构建请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("appCode", "my-iot-platform-device");
        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        // 构建请求体
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        CommonInputStreamResource commonInputStreamResource = null;
        try {
            commonInputStreamResource = new CommonInputStreamResource(multipartFile.getInputStream(),multipartFile.getSize(),multipartFile.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件输入流转换错误");
        }
        requestBody.add("upload_file", commonInputStreamResource);

        // 发送上传请求
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders);
        ResponseEntity<HashMap> responseEntity = restTemplate.postForEntity("http://my.imuyuan.com/file/upload/v5",
                requestEntity, HashMap.class);

优点:
不会生成临时文件,节省了内存.代码实现也不复杂,推荐使用.

  • 8
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值