当前位置:
首页 >
使用RestTemplate上传文件
发布时间:2023/12/8
39
豆豆
生活随笔
收集整理的这篇文章主要介绍了
使用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氪副总裁王坤:企服产品应重视
- 下一篇: 《文渊阁四库全书》书目