Example of downloading a file using Requester pay.
773832
public void downloadFileUsingRequesterPays(
      String projectId, String bucketName, String srcFilename, Path destFilePath)
      throws IOException {
    // [START storage_download_file_requester_pays]
    // The project ID to bill
    // String projectId = "my-billable-project-id";

    // The name of the bucket to access
    // String bucketName = "my-bucket";

    // The name of the remote file to download
    // String srcFilename = "file.txt";

    // The path to which the file should be downloaded
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

    // Instantiate a Google Cloud Storage client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get specific file from specified bucket
    Blob blob = storage.get(BlobId.of(bucketName, srcFilename));

    // Download file to specified path
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));
    // [END storage_download_file_requester_pays]
  }
434203
def download(spec, target = nil)
      if target.nil?
        ext = File.extname(spec['file_name'])
        base = File.basename(spec['file_name'], ext)
        target = Dir::Tmpname.create([base, ext]) {}
      end

      File.open(target, 'wb') do |output|
        retrieve(spec) do |chunk, retrieved, total|
          output.write(chunk)
          yield(target, retrieved, total) if block_given?
        end
      end
      target
    end
1081604
def download(url, filename=None):
	
	# requirements os, shutil, urllib.parse, urllib.request
	if not filename:
		url_parts = urllib.parse.urlparse(url)
		filename = os.path.basename(url_parts.path)
	url_h = urllib.request.urlopen(url)
	with open(filename, 'wb') as file_h:
		shutil.copyfileobj(url_h, file_h)
	url_h.close()
	return
193840
def download(self, request, **kwargs):
        

        # method check to avoid bad requests
        self.method_check(request, allowed=['get'])

        # create a basic bundle object for self.get_cached_obj_get.
        basic_bundle = self.build_bundle(request=request)

        # using the primary key defined in the url, obtain the tileset
        tileset = self.cached_obj_get(
            bundle=basic_bundle,
            **self.remove_api_resource_names(kwargs))

        filename = helpers.get_tileset_filename(tileset)
        filename = os.path.abspath(filename)
        if os.path.isfile(filename):
            response = serve(request, os.path.basename(filename), os.path.dirname(filename))
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(filename))
        else:
            response = self.create_response(request, {'status': 'not generated'})
        return response
212194
function download(uri, dest, progressCallback) {
    "use strict";
    progressCallback = progressCallback || function() {};
    var parsedUrl = url.parse(uri, false, true);
    var makeRequest = parsedUrl.protocol === 'https:' ? https.request.bind(https) : http.request.bind(http);
    var serverPort = parsedUrl.port ? parsedUrl.port : parsedUrl.protocol === 'https:' ? 443 : 80;
    var agent = parsedUrl.protocol === 'https:' ? httpsAgent : httpAgent;
    var file = fs.createWriteStream(dest);

    var options = {
        host: parsedUrl.host,
        path: parsedUrl.path,
        agent: agent,
        port: serverPort,
        method: 'GET'
    };

    return new Promise(function (resolve, reject) {

        var req = makeRequest(options, function (response) {
            var size = response.headers['content-length'];
            var progress = 0;

            response.on('data', function(chunk) {
                progress += chunk.length;
                progressCallback(size, progress);
            });

            response.pipe(file);
            file.on('finish', function() {
                resolve({
                    status: response.statusCode
                });
            });
        });

        req.on('error', function(error) {
            file.end();
            rimraf.sync(dest);
            reject(error);
        });

        req.end();
    });
}
1003906
def download(url):
    """"""
    session = requests.Session()
    session.mount('file://', FileAdapter())

    try:
        res = session.get(url)
    except requests.exceptions.ConnectionError as e:
        raise e

    res.raise_for_status()

    return res
286885
def download_url(url, filename, headers):
    """"""
    ensure_dirs(filename)
    response = requests.get(url, headers=headers, stream=True)
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            for chunk in response.iter_content(16 * 1024):
                f.write(chunk)
879866
def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
        

        local_file_name = local_file_name if local_file_name else url.split('/')[-1]
        filepath = os.path.join(cls.data_path, local_file_name)

        if not os.path.exists(filepath) or force:
            try:
                headers = requests.head(url, allow_redirects=True).headers
                length = headers.get('Content-Length')

                logger.info("Starting download of {} file with {} bytes ...".format(url, length))

                widgets = [
                    'Downloading file please wait...', progressbar.Percentage(),
                    ' ', progressbar.Bar(),
                    ' ', progressbar.ETA(),
                    ' ', progressbar.FileTransferSpeed(),
                ]
                bar = progressbar.ProgressBar(widgets=widgets, max_value=int(length) + chunk_size).start()

                r = requests.get(url, stream=True)

                with open(filepath, 'wb') as f:
                    total_chunk = 0

                    for chunk in r.iter_content(chunk_size):
                        if chunk:
                            f.write(chunk)
                            total_chunk += chunk_size
                            bar.update(total_chunk)

                bar.finish()

            except:
                if os.path.exists(filepath):
                    os.remove(filepath)

                raise

        return filepath
195719
def action_download(self, courseid, taskid, path):
        

        wanted_path = self.verify_path(courseid, taskid, path)
        if wanted_path is None:
            raise web.notfound()

        task_fs = self.task_factory.get_task_fs(courseid, taskid)
        (method, mimetype_or_none, file_or_url) = task_fs.distribute(wanted_path)

        if method == "local":
            web.header('Content-Type', mimetype_or_none)
            return file_or_url
        elif method == "url":
            raise web.redirect(file_or_url)
        else:
            raise web.notfound()
438282
def download(url, target_file, chunk_size=4096):
    
    r = requests.get(url, stream=True)

    with open(target_file, 'w+') as out:
        # And this is why I love Armin Ronacher:
        with click.progressbar(r.iter_content(chunk_size=chunk_size),
                               int(r.headers['Content-Length'])/chunk_size,
                               label='Downloading...') as chunks:
            for chunk in chunks:
                out.write(chunk)
1172293
def download_file(response)
      tmp_file = Tempfile.new '', Configuration.temp_folder_path
      content_disposition = response.headers['Content-Disposition']
      if content_disposition
        filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
        path = File.join File.dirname(tmp_file), filename
      else
        path = tmp_file.path
      end
      # close and delete temp file
      tmp_file.close!

      File.open(path, 'w') { |file| file.write(response.body) }
      Configuration.logger.info "File written to #{path}. Please move the file to a proper "\
                                "folder for further processing and delete the temp afterwards"
      File.new(path)
    end
1220856
def _downloadfile(self, url, fname):
        '''  '''

        print("The file %s need to be download - Wait\n " %
              (fname.split('/')[-1]))
        urllib.urlretrieve(url, fname, self._report)
        print("\n The download of the file %s has succeded \n " %
              (fname.split('/')[-1]))
1363338
function downloadFile(url, outputPath) {
	const dir = path.dirname(outputPath);
	if (!fs.existsSync(dir)) {
		fs.mkdirSync(dir);
	}
	return new Promise((resolve, reject) => {
		const file = fs.createWriteStream(outputPath);
		const sendReq = request.get(url);
		sendReq.pipe(file);

		sendReq
		.on("response", (response) => {
			if (response.statusCode !== 200) {
				fs.unlink(outputPath);
				const error = new Error("Response status code was " + response.statusCode + ".");
				console.trace(error);
				reject(error);
			}
		})
		.on("error", (error) => {
			fs.unlink(outputPath);
			console.trace(error);
			reject(error);
		});

		file
		.on("finish", () => {
			file.close(() => {
				resolve();
			});
		})
		.on("error", (error) => {
			fs.unlink(outputPath);
			console.trace(error);
			reject(error);
		});
	});
}
1303424
def download(input, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
    
    kwargs['format'] = format
    if resolvers:
        kwargs['resolver'] = ",".join(resolvers)
    url = API_BASE+'/%s/file?%s' % (urlquote(input), urlencode(kwargs))
    try:
        servefile = urlopen(url)
        if not overwrite and os.path.isfile(filename):
            raise IOError("%s already exists. Use 'overwrite=True' to overwrite it." % filename)
        file = open(filename, "w")
        file.write(servefile.read())
        file.close()
    except urllib.error.HTTPError:
        # TODO: Proper handling of 404, for now just does nothing
        pass
1116459
def from_url(cls, url, **kwargs):
    
    username = kwargs.get('username')
    password = kwargs.get('password')
    headers = kwargs.get('headers', {})
    auth = None
    path = kwargs.get('path', '/tmp/app.zip')
    dest = kwargs.get('dest', '/app')
    if username and password:
      auth = base64.b64encode(b'%s:%s' % (username, password))
    if auth:
      headers['Authorization'] = 'Basic %s' % auth.decode('utf8')
    r = request.get(url, headers=headers, stream=True)
    if r.status_code != 200:
      err_msg = 'Could not download resource from url (%s): %s'
      err_args = (r.status_code, url)
      raise errors.DownloadError(err_msg % err_args)
    with open('/tmp/app.zip', 'wb+') as f:
      chunks = r.iter_content(chunk_size=1024)
      [f.write(chunk) for chunk in chunks if chunk]
    return cls.from_zip(path, dest)
972217
def download_file(self, *args, **kwargs):
        """"""
        return download_file(*args, **self._merge_overrides(**kwargs)).run()
34762
def download_file(file_id, file_name):
    ''''''
    extracted_out_dir = os.path.join(app.config['UPLOAD_FOLDER'], file_id)
    return send_file(os.path.join(extracted_out_dir, file_name))