Download the image according to URL to a simple instance of the client and server

  • 2020-05-24 05:37:27
  • OfStack

1. Save to the server

Save to the server where the project is located according to the path.


String imgUrl="";// Picture address 
    try {
      //  structure URL
      URL url = new URL(imgUrl);
      //  Open the connection 
      URLConnection con = url.openConnection();
      //  The input stream 
      InputStream is = con.getInputStream();
      // 1K Data buffering 
      byte[] bs = new byte[1024];
      //  Length of data read 
      int len;
      //  Output file stream 
      OutputStream os = new FileOutputStream("c:\\image.jpg");// Save the path 
      //  Began to read 
      while ((len = is.read(bs)) != -1) {
        os.write(bs, 0, len);
      }
      //  Over, 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 to local 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();
    }

Related articles: