zoukankan      html  css  js  c++  java
  • 根据url地址单个或批量下载图片

    我们在java开发的时候会遇到通过url地址下载图片的情况。方便起见,我把通过url地址下载图片封装了tool工具类,方便以后使用
    1.根据如:http://abc.com/hotels/a.jpg 的url地址下载文件(图片)
     
     
    //调用下面的方法
    download(urlString, filename, savePath+"/"+String.valueOf(imgList.get(i).get("hotelId")));
     
    /**
    * 根据路径 下载图片 然后 保存到对应的目录下
    * @param urlString 下载源地址路径 http://media.expedia.com/hotels/1000000/10000/100/1/1_17_b.jpg
    * @param filename 文件名
    * @param savePath 保存路径 /jdylog/pic/JDY000001
    * @return
    * @throws Exception
    */
    public void download(String urlString, String filename,String savePath) throws Exception {
    // 构造URL
    // System.setProperty("http.proxySet", "true");
    // System.setProperty("http.proxyHost", "192.168.2.138");
    // System.setProperty("http.proxyPort", "1081");
    URL url = new URL(urlString);
    // 打开连接
    URLConnection con = url.openConnection();
    //设置请求的路径
    con.setConnectTimeout(5*1000);
    // 输入流
    InputStream is = con.getInputStream();
     
    // 1K的数据缓冲
    byte[] bs = new byte[1024];
    // 读取到的数据长度
    int len;
    // 输出的文件流
    File sf=new File(savePath);
    if(!sf.exists()){
    sf.mkdirs();
    }
    OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);
    // 开始读取
    while ((len = is.read(bs)) != -1) {
    os.write(bs, 0, len);
    }
    // 完毕,关闭所有链接
    os.close();
     
    is.close();
    }
  • 相关阅读:
    面相对象2016/4/19
    2016/4/19
    ajax2016/4/15 post与get
    iframe2016/4/12
    Hibernate报错解决Error parsing JNDI name [],Need to specify class name
    vue-router 源码解析最简版
    vue数据响应式原理
    3-箭头函数与普通函数
    2.1.7 html的处理与打包
    2.1.6 css的编译与处理 -2
  • 原文地址:https://www.cnblogs.com/dongzhongwei/p/5964731.html
Copyright © 2011-2022 走看看