RestTemplate實現文件上傳和下載接口

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);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章