Downloads this message attachments into memory.
        Need a call to 'attachment.save' to save them on disk.

        :return: Success / Failure
        :rtype: bool
168037
def download_attachments(self):
        
        if not self._parent.has_attachments:
            log.debug(
                'Parent {} has no attachments, skipping out early.'.format(
                    self._parent.__class__.__name__))
            return False

        if not self._parent.object_id:
            raise RuntimeError(
                'Attempted to download attachments of an unsaved {}'.format(
                    self._parent.__class__.__name__))

        url = self.build_url(self._endpoints.get('attachments').format(
            id=self._parent.object_id))

        response = self._parent.con.get(url)
        if not response:
            return False

        attachments = response.json().get('value', [])

        # Everything received from cloud must be passed as self._cloud_data_key
        self.untrack = True
        self.add({self._cloud_data_key: attachments})
        self.untrack = False

        # TODO: when it's a item attachment the attachment itself
        # is not downloaded. We must download it...
        # TODO: idea: retrieve the attachments ids' only with
        # select and then download one by one.
        return True
385711
def download(objects):
    
    def exists(object):
        if os.path.exists(TMPDIR + '/' + filename):
            return True
        else:
            msg = 'File object %s failed to download to %s. Exit' % (filename, TMPDIR)
            logger.warning(msg)
            stdout_message('%s: %s' % (inspect.stack()[0][3], msg))
            return False
    try:
        for file_path in objects:
            filename = file_path.split('/')[-1]
            r = urllib.request.urlretrieve(file_path, TMPDIR + '/' + filename)
            if not exists(filename):
                return False
    except urllib.error.HTTPError as e:
        logger.exception(
            '%s: Failed to retrive file object: %s. Exception: %s, data: %s' %
            (inspect.stack()[0][3], file_path, str(e), e.read()))
        raise e
    return True
675053
def download_slides(self):
        
        return self.presentation.client.download_all(self.presentation.metadata['slides'], self.tmp_dir)
1242836
def save_downloaded_file(filename, save_file_at, file_stream):
        
        filename = os.path.join(save_file_at, filename)
        with open(filename, 'wb') as f:
            f.write(file_stream)
            f.flush()
400302
def save_as_header(self, response, **kwargs):
        
        save_as = kwargs.get('save_as', None)
        if save_as is False:
            return
        file_obj = kwargs.get('file_obj', None)
        if save_as is True or save_as is None:
            filename = os.path.basename(file_obj.path)
        else:
            filename = save_as
        response['Content-Disposition'] = smart_str(
            'attachment; filename=%s' % filename)
940838
def download_files(files):
    ''''''
    for (url, file) in files:
        print("Downloading %s as %s" % (url, file))
        data = download_url(url)
        if data is None:
            continue
        try:
            open(file, mode='wb').write(data)
        except Exception as e:
            print("Failed to save to %s : %s" % (file, e))
938336
def download_object(self, obj_name, directory, structure=True):
        
        return self.download(obj=obj_name, directory=directory,
                structure=structure)
1260950
def _on_bytes_read(self, num_bytes_read):
        
        self.actual_bytes_read += num_bytes_read
        if self.actual_bytes_read > self.bytes_to_read:
            raise TooLargeChunkDownloadError(self.actual_bytes_read, self.bytes_to_read, self.local_path)
        self.download_context.send_processed_message(num_bytes_read)
289334
def download(self):
        
        # Prepare output path
        self.output_file = QFile(self.output_path)
        if not self.output_file.open(QFile.WriteOnly):
            raise IOError(self.output_file.errorString())

        # Prepare downloaded buffer
        self.downloaded_file_buffer = QByteArray()

        # Request the url
        request = QNetworkRequest(self.url)
        self.reply = self.manager.get(request)
        self.reply.readyRead.connect(self.get_buffer)
        self.reply.finished.connect(self.write_data)
        self.manager.requestTimedOut.connect(self.request_timeout)

        if self.progress_dialog:
            # progress bar
            def progress_event(received, total):
                """Update progress.

                :param received: Data received so far.
                :type received: int

                :param total: Total expected data.
                :type total: int
                """
                # noinspection PyArgumentList
                QgsApplication.processEvents()

                self.progress_dialog.adjustSize()

                human_received = humanize_file_size(received)
                human_total = humanize_file_size(total)

                label_text = tr("%s : %s of %s" % (
                    self.prefix_text, human_received, human_total))

                self.progress_dialog.setLabelText(label_text)
                self.progress_dialog.setMaximum(total)
                self.progress_dialog.setValue(received)

            # cancel
            def cancel_action():
                """Cancel download."""
                self.reply.abort()
                self.reply.deleteLater()

            self.reply.downloadProgress.connect(progress_event)
            self.progress_dialog.canceled.connect(cancel_action)

        # Wait until finished
        # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always
        # returns False even after finished slot is called. So, that's why we
        # are adding self.finished_flag (see #864)
        while not self.reply.isFinished() and not self.finished_flag:
            # noinspection PyArgumentList
            QgsApplication.processEvents()

        result = self.reply.error()
        try:
            http_code = int(self.reply.attribute(
                QNetworkRequest.HttpStatusCodeAttribute))
        except TypeError:
            # If the user cancels the request, the HTTP response will be None.
            http_code = None

        self.reply.abort()
        self.reply.deleteLater()

        if result == QNetworkReply.NoError:
            return True, None

        elif result == QNetworkReply.UnknownNetworkError:
            return False, tr(
                'The network is unreachable. Please check your internet '
                'connection.')

        elif http_code == 408:
            msg = tr(
                'Sorry, the server aborted your request. '
                'Please try a smaller area.')
            LOGGER.debug(msg)
            return False, msg

        elif http_code == 509:
            msg = tr(
                'Sorry, the server is currently busy with another request. '
                'Please try again in a few minutes.')
            LOGGER.debug(msg)
            return False, msg

        elif result == QNetworkReply.ProtocolUnknownError or \
                result == QNetworkReply.HostNotFoundError:
            # See http://doc.qt.io/qt-5/qurl-obsolete.html#encodedHost
            encoded_host = self.url.toAce(self.url.host())
            LOGGER.exception('Host not found : %s' % encoded_host)
            return False, tr(
                'Sorry, the server is unreachable. Please try again later.')

        elif result == QNetworkReply.ContentNotFoundError:
            LOGGER.exception('Path not found : %s' % self.url.path())
            return False, tr('Sorry, the layer was not found on the server.')

        else:
            return result, self.reply.errorString()
299226
def download(url, filename, overwrite = False):
	'''  '''

	from requests import get
	from os.path import exists

	debug('Downloading ' + unicode(url) + '...')
	data = get(url)
	if data.status_code == 200:
		if not exists(filename) or overwrite:
			f = open(filename, 'wb')
			f.write(data.content)
			f.close()
		return True
	return False
852216
def _download(self, force_overwrite=False, verbose=False):
        
        if not force_overwrite:
            # If the file is already there, we're done
            if os.path.isfile(self.filepath):
                if verbose:
                    print(
                        "File already available at %s -- skipping"
                        % (self.filepath)
                    )
                return False
        stream_download(self.URL, self.filepath, verbose=verbose)
        return True
838736
def download_url(url, save_as, iter_size=_default_iter_size, enable_verbose=True):
    
    msg = Messenger()
    if enable_verbose:
        msg.on()
    else:
        msg.off()

    msg.show("Downloading %s from %s..." % (save_as, url))

    with open(save_as, "wb") as f:
        response = requests.get(url, stream=True)

        if not response.ok:
            print("http get error!")
            return

        start_time = time.clock()
        downloaded_size = 0
        for block in response.iter_content(iter_size):
            if not block:
                break
            f.write(block)
            elapse = datetime.timedelta(seconds=(time.clock() - start_time))
            downloaded_size += sys.getsizeof(block)
            msg.show("    Finished %s, elapse %s." % (
                string_SizeInBytes(downloaded_size), elapse
            ))

    msg.show("    Complete!")
851738
def init_attachment_cache(self):
        
        if self.request.method == 'GET':
            # Invalidates previous attachments
            attachments_cache.delete(self.get_attachments_cache_key(self.request))
            return

        # Try to restore previous uploaded attachments if applicable
        attachments_cache_key = self.get_attachments_cache_key(self.request)
        restored_attachments_dict = attachments_cache.get(attachments_cache_key)
        if restored_attachments_dict:
            restored_attachments_dict.update(self.request.FILES)
            self.request._files = restored_attachments_dict

        # Updates the attachment cache if files are available
        if self.request.FILES:
            attachments_cache.set(attachments_cache_key, self.request.FILES)
338695
def download_files(self, files):
        
        utils.pending_message(
            "Downloading {nfiles} file{plural}...".format(
                nfiles=len(files),
                plural='s' if len(files) > 1 else ''
            ))

        for file in files:
            if 'file_id' not in file:
                continue

            def build_callback(file):
                """Callback to save a download file result to a file on disk."""
                def file_callback(task):
                    device_name = self.devices[self.device_id]['device_name']
                    path_chunks = file['file_path'].split('/')

                    directory = os.path.join('files', device_name, *path_chunks[:-1])

                    filepath = utils.get_or_create_filepath(file['filename'], directory)

                    with open(filepath, 'wb') as out:
                        out.write(task.result)

                    if settings.getboolean('logging', 'time_profile'):
                        filepath = utils.append_profile_info(filepath, task.timer)

                    with indent(4):
                        utils.print_message(filepath)

                return file_callback

            self.client.download_file(
                account=self.account,
                device=self.device_id,
                file=file['file_id'],
                callback=build_callback(file)
            )
376702
public function download_attachments()
    {
        $rcmail = rcmail::get_instance();

        // require CSRF protected request
        $rcmail->request_security_check(rcube_utils::INPUT_GET);

        $imap      = $rcmail->get_storage();
        $temp_dir  = $rcmail->config->get('temp_dir');
        $tmpfname  = tempnam($temp_dir, 'zipdownload');
        $tempfiles = array($tmpfname);
        $message   = new rcube_message(rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET));

        // open zip file
        $zip = new ZipArchive();
        $zip->open($tmpfname, ZIPARCHIVE::OVERWRITE);

        foreach ($message->attachments as $part) {
            $pid      = $part->mime_id;
            $part     = $message->mime_parts[$pid];
            $disp_name = $this->_create_displayname($part);

            $tmpfn       = tempnam($temp_dir, 'zipattach');
            $tmpfp       = fopen($tmpfn, 'w');
            $tempfiles[] = $tmpfn;

            $message->get_part_body($part->mime_id, false, 0, $tmpfp);
            $zip->addFile($tmpfn, $disp_name);
            fclose($tmpfp);
        }

        $zip->close();

        $filename = ($this->_filename_from_subject($message->subject) ?: 'attachments') . '.zip';

        $this->_deliver_zipfile($tmpfname, $filename);

        // delete temporary files from disk
        foreach ($tempfiles as $tmpfn) {
            unlink($tmpfn);
        }

        exit;
    }
511049
async def download_media(self, *args, **kwargs):
        
        return await self._client.download_media(self, *args, **kwargs)
131841
function download()
    {
        if (!$this->card) {
            $this->build();
        }

        if (!$this->filename) {
            $this->filename = $this->data['display_name'];
        }

        $this->filename = str_replace(' ', '_', $this->filename);

        header("Content-type: text/directory");
        header("Content-Disposition: attachment; filename=" . $this->filename . ".vcf");
        header("Pragma: public");
        echo $this->card;

        return true;
    }