file association没有 *.class文件_springboot如何MultipartFile文件跨服务
大家好,因為近期做需求中遇到了文件上傳這個東西,而且我這個還是跨服務去傳輸文件的所以我這邊使用了httpclient和RestTemplate去做,但是最后還是用的httpclient。feign和RestTemplate在超大文件下會OOM所以適用于小文件傳輸我這邊測試的在1G以下。httpclient好像是無限哈哈哈。(具體多少大家有時間可以去測一下)
1.被調用服務的Controller
1.這塊使用@RequestParam(“file”)或者@RequestPart(“file”)都是可以接到參數的。
2.(“file”)一定要和遠程調用代碼傳的參數名一樣 否則接不到參數。
1.RestTemplate
1.如果用RestTemplate的話首先需要把RestTemplate交給spring去管理所以先來一個配置類。
2.@SuppressWarnings(“all”) 這個注解是jdk自帶的的意思是 意志所有的警告。
2.RestTemplate遠程調用文件傳輸
這里有幾個要注意的地方
1.必須重寫否則傳輸時報錯
ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()) { @Override public String getFilename() { return file.getOriginalFilename(); } };2.設置請求頭因為就在模擬前端發送上傳文件的請求所以請求頭必須是multipart/form-data
3.第三個參數是被調用Controller的返回值類型,我的測試Controller寫的是String所以我的這邊第三參數就是String.Class
restTemplate.postForObject(url, files, String.class);4.url就是被調用服務的地址 如:
http://192.168.3.7:50003/test/remoteCallUpload以上是注意事項。
@Autowiredprivate 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 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> files = new HttpEntity<>(form, headers); String flag = restTemplate.postForObject(url, files, String.class); return flag; }12345678910111213141516171819202122233.HttpClient
1.使用httpclient的話首先要引入pom文件坐標。
org.apache.httpcomponents httpclient 4.5.6org.apache.httpcomponents httpmime 4.5.6123456789103.HttpClient遠程調用文件傳輸
1.httpclient這段代碼有要用的小伙伴直接粘過去就能用
注意一下返回值自己改一下就行execute.getEntity()
總結
遠程調用使用了RestTemplate和httpclient也可以使用feign,但是RestTemplate和feign大文件會OOM,httpclient不會所以大家可以根據自己場景去選擇。
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的file association没有 *.class文件_springboot如何MultipartFile文件跨服务的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Ubuntu中apt与apt-get命令
- 下一篇: android最简单存储数据结构,什么是
