Download image from given url and saves it to destination.
545724
def load_and_save_image(url, destination):
    """"""
    from urllib2 import Request, urlopen, URLError, HTTPError
    # create the url and the request
    req = Request(url)

    # Open the url
    try:
        f = urlopen(req)
        print "downloading " + url

        # Open our local file for writing

        local_file = open(destination, "wb")
        # Write to our local file
        local_file.write(f.read())
        local_file.close()

        file_type = imghdr.what(destination)
        local_file = open(destination, "rb")
        data = local_file.read()
        local_file.close()

        final_file = open(destination + '.' + file_type, "wb")
        final_file.write(data)
        final_file.close()
        print('save image preview {0}'.format(destination + '.' + file_type))
        os.remove(destination)

    # handle errors
    except HTTPError, e:
        print "HTTP Error:", e.code, url
    except URLError, e:
        print "URL Error:", e.reason, url
5172
def download_to(self, folder):
        '''
        
        '''
        urlretrieve(self.maven_url, os.path.join(folder, self.filename))
228997
def generate_image_from_url(url=None, timeout=30):
    

    file_name = posixpath.basename(url)
    img_tmp = NamedTemporaryFile(delete=True)

    try:
        response = requests.get(url, timeout=timeout)
        response.raise_for_status()
    except Exception as e:  # NOQA
        return None, None

    img_tmp.write(response.content)
    img_tmp.flush()

    image = File(img_tmp)
    image.seek(0)

    return file_name, image
994904
public static void downloadFile(URL url, File destination) throws IOException {
		int count = 0;
		int maxTries = 10;
		int timeout = 60000; //60 sec

		File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination));

		// Took following recipe from stackoverflow:
		// http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java
		// It seems to be the most efficient way to transfer a file
		// See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html
		ReadableByteChannel rbc = null;
		FileOutputStream fos = null;
		while (true) {
			try {
				URLConnection connection = prepareURLConnection(url.toString(), timeout);
				connection.connect();
				InputStream inputStream = connection.getInputStream();

				rbc = Channels.newChannel(inputStream);
				fos = new FileOutputStream(tempFile);
				fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
				break;
			} catch (SocketTimeoutException e) {
				if (++count == maxTries) throw e;
			} finally {
				if (rbc != null) {
					rbc.close();
				}
				if (fos != null) {
					fos.close();
				}
			}
		}

		logger.debug("Copying temp file {} to final location {}", tempFile, destination);
		copy(tempFile, destination);

		// delete the tmp file
		tempFile.delete();

	}
1252872
def _convert_url_to_downloadable(url):
    """"""

    if 'drive.google.com' in url:
        # For future support of google drive
        file_id = url.split('d/')[1].split('/')[0]
        base_url = 'https://drive.google.com/uc?export=download&id='
        out = '{}{}'.format(base_url, file_id)
    elif 'dropbox.com' in url:
        if url.endswith('.png'):
            out = url + '?dl=1'
        else:
            out = url.replace('dl=0', 'dl=1')
    elif 'github.com' in url:
        out = url.replace('github.com', 'raw.githubusercontent.com')
        out = out.replace('blob/', '')
    else:
        out = url
    return out
483297
def download_image(self, handle, dest):
        
        shutil.copyfile(self._prefixed(handle), dest)
329564
def download(self, source, destination):
        """"""
        self._handler.download(posix_path(source), destination)
934169
function download(url) {
  return request('GET', url).then(function (res) {
    var out = {
      url: url,
      body: res.body,
      statusCode: res.statusCode,
      headers: res.headers,
      dependencies: []
    };

    try {
      if (out.statusCode === 302) {
        out.dependencies = [out.headers.location];
      } else if (!out.headers['content-type']) {
        out.dependencies = [];
      } else if (out.headers['content-type'].indexOf('text/html') !== -1) {
        out.dependencies = htmldeps(out.body.toString());
      } else if (out.headers['content-type'].indexOf('text/css') !== -1) {
        out.dependencies = cssdeps(out.body.toString());
      } else {
        out.dependencies = [];
      }
    } catch (ex) {
      ex.message = 'Error parsing deps for "' + url + '": ' + ex.message;
      throw ex;
    }
    return out;
  });
}
118460
def download(self, remote_url, local_path, buffer_size=8 * 1024):
        """"""
        bucket, key = _parse_url(remote_url)

        response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
        with open(local_path, 'wb') as fp:
            buf = response_file.read(buffer_size)
            while buf:
                fp.write(buf)
                buf = response_file.read(buffer_size)
1234298
def save(url, destination):
    
    r = requests.get(url, stream=True)

    with open(destination, 'wb') as fd:
        for chunk in r.iter_content(chunk_size=128):
            fd.write(chunk)
390182
def download_url(url, back_off=True, **kwargs):
    
    if back_off:
        return _download_with_backoff(url, as_file=True, **kwargs)
    else:
        return _download_without_backoff(url, as_file=True, **kwargs)
261504
def download_from_url(source, destination, progress=False, uncompress=False):
    """"""
    # Modules #
    from tqdm import tqdm
    import requests
    from autopaths.file_path import FilePath
    # Check destination exists #
    destination = FilePath(destination)
    destination.directory.create_if_not_exists()
    # Over HTTP #
    response = requests.get(source, stream=True)
    total_size = int(response.headers.get('content-length'))
    block_size = int(total_size/1024)
    # Do it #
    with open(destination, "wb") as handle:
        if progress:
            for data in tqdm(response.iter_content(chunk_size=block_size), total=1024): handle.write(data)
        else:
            for data in response.iter_content(chunk_size=block_size): handle.write(data)
    # Uncompress #
    if uncompress:
        with open(destination) as f: header = f.read(4)
        if header == "PK\x03\x04": unzip(destination, inplace=True)
        # Add other compression formats here
    # Return #
    return destination
1198309
protected Bitmap downloadBitmap(String url, BitmapOptions options) throws Exception {
    AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    HttpGet getRequest = new HttpGet(url);

    try {
      HttpResponse response = client.execute(getRequest);
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != HttpStatus.SC_OK) {
        // we could check the status, but we'll just assume that if there's a Location header,
        // we should follow it
        Header[] headers = response.getHeaders("Location");
        if (headers != null && headers.length > 0) {
          return downloadBitmap(headers[headers.length-1].getValue(), options);
        }
        throw new Exception("Error " + statusCode + " while retrieving bitmap from " + url);
      }

      HttpEntity entity = response.getEntity();
      if (entity == null)
        throw new Exception("Error: getEntity returned null for " + url);

      InputStream inputStream = null;
      try {
        inputStream = entity.getContent();
        return BitmapFactory.decodeStream(inputStream, null, options);
      } finally {
        if (inputStream != null)
          inputStream.close();
        entity.consumeContent();
      }

    } catch (Exception e) {
      // Could provide a more explicit error message for IOException or IllegalStateException
      getRequest.abort();
      plat.reportError("Error while retrieving bitmap from " + url, e);
      throw e;

    } finally {
      client.close();
    }
  }
1213357
def save_file_as(self, file_url, new_file_name, destination_folder=None):
        
        if not destination_folder:
            destination_folder = constants.Files.DOWNLOADS_FOLDER
        page_utils._download_file_to(
            file_url, destination_folder, new_file_name)
747194
def downloadThumbnail(self, outPath):
        """"""
        url = self._url + "/info/thumbnail"
        params = {

        }
        return self._get(url=url,
                            out_folder=outPath,
                            file_name=None,
                            param_dict=params,
                            securityHandler=self._securityHandler,
                            proxy_url=self._proxy_url,
                            proxy_port=self._proxy_port)
920129
def download_pic(self, filename: str, url: str, mtime: datetime,
                     filename_suffix: Optional[str] = None, _attempt: int = 1) -> bool:
        """"""
        urlmatch = re.search('\\.[a-z0-9]*\\?', url)
        file_extension = url[-3:] if urlmatch is None else urlmatch.group(0)[1:-1]
        if filename_suffix is not None:
            filename += '_' + filename_suffix
        filename += '.' + file_extension
        # A post is considered "commited" if the json file exists and is not malformed.
        if self.commit_mode:
            if self._committed and os.path.isfile(filename):
                self.context.log(filename + ' exists', end=' ', flush=True)
                return False
        else:
            if os.path.isfile(filename):
                self.context.log(filename + ' exists', end=' ', flush=True)
                return False
        self.context.get_and_write_raw(url, filename)
        os.utime(filename, (datetime.now().timestamp(), mtime.timestamp()))
        return True
948121
def download_file(url, filename):
    """"""
    r = _get_requests_session().get(url, stream=True)
    if not r.ok:
        raise IOError("Unable to download file")

    with open(filename, "wb") as f:
        f.write(r.content)