使用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 会通过这个方法获取大小。然后当真正需要读取内容的时候,发现已经读完,会报如下错误。
     * 
     * 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)
     * 
     * 

* 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);

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

你可能感兴趣的:(springMVC,resttemplate)