(直接下載url檔案)使用Apache Httpclient訪問Spring rest介面下載檔案
阿新 • • 發佈:2019-01-05
1.編寫Spring rest介面,該介面將檔案讀入到流中並通過ResponseEntity物件返回
@RequestMapping(value="/file",method=RequestMethod.GET)
public ResponseEntity<InputStreamResource> getFile(@RequestParam Integer id){
//設定response返回頭部資訊
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must- revalidate" );
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
FileInputStream input=null;
File file=null;
long len=0l;
try {
//通過主鍵ID獲取檔案物件
FileData data=fileMapper.selectByPrimaryKey(id);
//獲取檔案儲存的路徑
String filePath=data.getFilePath();
//通過Paths獲取檔案
file=Paths.get(filePath).toFile();
input=new FileInputStream(file);
len=file.length();
} catch (Exception e) {
e.printStackTrace();
}
//設定返回實體的頭部、長度及型別
return ResponseEntity
.ok()
.headers(headers)
.contentLength(len)
.contentType(MediaType.parseMediaType("application/octet-stream" ))
.body(new InputStreamResource(input));
}
2.應用二使用httpclient傳送請求獲取檔案流,然後將檔案流寫入到檔案中實現檔案下載功能
@RequestMapping(value="/file/download/{id}",method=RequestMethod.GET)
public OperationResult downloadFile(@PathVariable(value="id") Integer id,
HttpServletResponse response){
//根據主鍵ID從資料庫中查詢檔案資訊
Map<String,Object> originalDataMap=fileMapper.findFileByPrimaryKey(id);
//獲取檔案的名稱(包含字尾)
String oldFileName=String.valueOf(originalDataMap.get("original_title"));
byte[] buffer= new byte[1024];
//char[] buffer= new char[1024];
int len=-1;
//建立httpClient客戶端
CloseableHttpClient httpClient=HttpClients.createDefault();
//建立httpGet傳送請求獲取檔案
HttpGet httpGet=new HttpGet("http://localhost:8080/test?id="+id);
//將檔案讀入到輸入流中
try(CloseableHttpResponse httpResponse=httpClient.execute(httpGet);
InputStream input=httpResponse.getEntity().getContent();
OutputStream output=response.getOutputStream();
){
//設定響應頭
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(oldFileName, "UTF-8")); //從輸入流中讀取檔案
while((len=input.read(buffer))!=-1){
//將buffer陣列寫入到檔案中,從0開始寫入的長度為實際讀取到的長度len,如果使用write(buffer);會出現中文亂碼及影象變模糊的問題
output.write(buffer,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}