JavaはURLに基づいて画像をローカルにダウンロードすることを実現する
4405 ワード
@GetMapping(value="/download")
public Map,Object> downloadFile( HttpServletResponse response){
byte[] buffer= new byte[1024];
int len=-1;
// httpClient
CloseableHttpClient httpClient=HttpClients.createDefault();
// httpGet
HttpGet httpGet=new HttpGet("https://image.baidu.com/test.jpg");
//
try(CloseableHttpResponse httpResponse=httpClient.execute(httpGet);
InputStream input=httpResponse.getEntity().getContent();
OutputStream output=response.getOutputStream();
){
//
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(new Date().getTime()+".jpg", "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();
}
return null;
}