0 背景
项目中需要调用第三方导入文件和导出文件接口,本文采用RestTemplate调用接口
1 上传文件
// 导入文件
RestTemplate restTemplate = new RestTemplate();
String file = "d:\\test.zip"; //或者File类型文件
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(2); //需要MultiValueMap数据结构
map.add("key","value");
map.add("file",new FileSystemResource(file)); //需要FileSystemResource将路径转为文件
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map,headers);
ResponseEntity<String> response = restTemplate.postForEntity(url,request,String.class);
2 下载文件
// 导出文件
String var1 = ""; //url包含的路径参数
File file1 = restTemplate.execute(url,HttpMethod.GET,clientHttpRequest ->{
HttpHeaders headers1 = new HttpHeaders();
headers1.add("content-type","application/zip");
headers1.add("content-disposition","attachment; filename=export-single.zip"); //添加头文件
},clientHttpResponse -> {
File ret = File.createTempFile("export",".zip"); //生成导出文件的命名("export"+"随机字符"+".zip")
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
},var1);
// 导出文件之后到浏览器直接下载
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDispositionFormData("attachment",file1.getName());
return new ResponseEntity<Resource>(new FileSystemResource(file),httpHeaders,HttpStatus.OK);
3 将一个java对象转化为json字符串并下载
// 使用工具 fastjson
//已有对象 user
InputStream inputStream = new ByteArrayInputStream(JSONArray.toJSONString(user).getBytes()); //fastjson将java对象转化为json字符串
//需要处理异常
File ret = File.createTempFile("export",".json"); //生成导出文件的命名("export"+"随机字符"+".json")
StreamUtils.copy(inputStream , new FileOutputStream(ret));
// 浏览器直接下载
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDispositionFormData("attachment",ret.getName());
return new ResponseEntity<Resource>(new FileSystemResource(file),httpHeaders,HttpStatus.OK);