How does springboot MultipartFile file transfer across services

Hello everyone, because I encountered file uploading in recent requirements, and I still transfer files across services, I used httpclient and RestTemplate to do this, but I still used httpclient in the end . Feign and RestTemplate will be OOM under oversized files, so they are suitable for small file transfer . The ones I tested here are below 1G . httpclient seems to be unlimited hahaha. (How much time do you have time to test it)

1. The Controller of the called service

1. Use @RequestParam("file") or @RequestPart("file") in this block to receive parameters.
2. ("file") must be the same as the parameter name passed by the remote call code, otherwise the parameter will not be received.

    @RequestMapping(value = "/remoteCallUpload",method = RequestMethod.POST)
    @ApiOperation("测试远程调用上传")
    public String remoteCallUpload(@RequestParam("file") MultipartFile file){
        System.out.println(file);
        return "成功";
    }

1.RestTemplate

1. If you use RestTemplate, you first need to give the RestTemplate to spring for management, so first come a configuration class.
2. @SuppressWarnings("all") This annotation is included in jdk, which means all warnings of the will.

@Configuration
@SuppressWarnings("all")
public class RestTemplateConfig {

    @Autowired
    RestTemplateBuilder builder;

    @Bean
    public RestTemplate restTemplate() {
        return builder.build();
    }
}

2. RestTemplate remote call file transfer

Here are a few things to pay attention to

1. Must be rewritten otherwise an error will be reported during transmission

ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        };

2. Set the request header because the request to upload the file is sent at the analog front end, so the request header must be multipart/form-data

3. The third parameter is the return value type of the called Controller. My test Controller writes String, so my third parameter here is String.Class

restTemplate.postForObject(url, files, String.class);

4.url is the address of the called service such as:

http://192.168.3.7:50003/test/remoteCallUpload

The above are precautions.

@Autowired
private RestTemplate restTemplate;

private String gettestRestTemplate(MultipartFile file, String url) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        };
        form.add("file", byteArrayResource);
        form.add("filename", file.getOriginalFilename());
        //用HttpEntity封装整个请求报文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        String flag = restTemplate.postForObject(url, files, String.class);

        return flag;
    }
1234567891011121314151617181920212223

3.HttpClient

1. If you use httpclient, you must first import the pom file coordinates.

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.6</version>
        </dependency>
12345678910

3. HttpClient remote call file transfer

1. The httpclient code has a small partner who needs to use
it and can be used directly. Note the return value and change it by yourself. execute.getEntity()

	@SneakyThrows
    private String gettesthttpclient(MultipartFile file, String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(10000)
                .setConnectTimeout(5000)
                .build();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        // 解决中文文件名乱码问题
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entityBuilder.setCharset(Consts.UTF_8);
        ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), Consts.UTF_8);
        entityBuilder.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, file.getOriginalFilename());
        httpPost.setEntity(entityBuilder.build());
        httpPost.setConfig(requestConfig);
        HttpResponse execute = httpclient.execute(httpPost);
        String flag = EntityUtils.toString(execute.getEntity());
        return flag;
    }

to sum up

Remote call using RestTemplate and httpclient can also use feign, but RestTemplate and feign large files will be OOM, httpclient will not, so you can choose according to your own scenario.

How does springboot MultipartFile file cross-service

Guess you like

Origin blog.csdn.net/a159357445566/article/details/112480442