使用RestTemplate上传文件
生活随笔
收集整理的這篇文章主要介紹了
使用RestTemplate上传文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫作目的
最近維護一個項目,里面用了RestTemplate進行服務之前的調用,不過最近有一個Excel解析的需求,百度了幾篇,內容不是很全,所以寫篇博客記錄一下,不過我還是推薦使用Feign調用,畢竟面向接口編程,方便。
代碼
親測可用
@RestController public class DataExcelImportController {private static final String REST_URL_PRFIX = "http://abc";@Autowiredprivate RestTemplate restTemplate;@PostMapping("/importExcel")public Object explainExcel(Integer stationId, @RequestPart("file") MultipartFile file) throws Exception {if (file.isEmpty()) {return "文件為空";}FdcpResult result = null;File file1 = null;try {//轉換為filefile1 = multipartFileToFile(file);FileSystemResource resource = new FileSystemResource(file1);MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();//參數param.add("file", resource);param.add("stationId", stationId);HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param);ResponseEntity<FdcpResult> responseEntity = restTemplate.exchange(REST_URL_PRFIX + "/importExcel", HttpMethod.POST, httpEntity, FdcpResult.class);result = responseEntity.getBody();} catch (Exception e) {e.printStackTrace();} finally {if (null != file) {//最后要刪除file1.delete();}}return result;}public static File multipartFileToFile(MultipartFile file) throws Exception {File toFile = null;if (file.equals("") || file.getSize() <= 0) {file = null;} else {InputStream ins = null;ins = file.getInputStream();toFile = new File(file.getOriginalFilename());inputStreamToFile(ins, toFile);ins.close();}return toFile;}//獲取流文件private static void inputStreamToFile(InputStream ins, File file) {try {OutputStream os = new FileOutputStream(file);int bytesRead = 0;byte[] buffer = new byte[8192];while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {os.write(buffer, 0, bytesRead);}os.close();ins.close();} catch (Exception e) {e.printStackTrace();}}}參考
使用RestTemplate上傳文件 - 簡書
MultipartFile轉File_唐僧洗發用飄柔-CSDN博客_multipartfile轉file
總結
以上是生活随笔為你收集整理的使用RestTemplate上传文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 科创人·36氪副总裁王坤:企服产品应重视
- 下一篇: 《文渊阁四库全书》书目