1. Save to the server
Save it to the server where the project is located according to the path.
String imgUrl="";//Image address try { //Construct URL URL url = new URL(imgUrl); // Open connection URLConnection con = url.openConnection(); // Input stream InputStream is = con.getInputStream(); // 1K data buffering byte[] bs = new byte[1024]; // Read data length int len; // Output file stream OutputStream os = new FileOutputStream("c://image.jpg");//Save path// Start reading while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } // Complete, close all links os.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }2. Save to local
Save locally as a browser download.
String imgUrl="";//URL address String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1); BufferedInputStream is = null; BufferedOutputStream os = null; try { URL url = new URL(imgUrl); this.getServletResponse().setContentType("application/x-msdownload;"); this.getServletResponse().setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); this.getServletResponse().setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength())); is = new BufferedInputStream(url.openStream()); os = new BufferedOutputStream(this.getServletResponse().getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = is.read(buff, 0, buff.length))) { os.write(buff, 0, bytesRead); } if (is != null) is.close(); if (os != null) os.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }The above simple example of downloading pictures to clients and servers based on URLs is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.