Java实现根据URL下载图片到本地

@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;
}

你可能感兴趣的:(Java实现根据URL下载图片到本地)