Downloads a file from the FTP server

@param string $localFile
@param string $remoteFile
@param int $mode
@param int $resumepos

@return FTPClient
429749
public function get($localFile, $remoteFile, $resumePosision = 0)
    {
        $mode = $this->getMode();
        $result = @ftp_get($this->connection, $localFile, $remoteFile, $mode, $resumePosision);

        if ($result === false)
        {
            throw new Exception(sprintf('Unable to get or save file "%s" from %s', $localFile, $remoteFile));
        }

        return $this;
    }
640435
def get_remote_file(self, remote_path, local_path):
        
        sftp_client = self.transport.open_sftp_client()
        LOG.debug('Get the remote file. '
                  'Source=%(src)s. Target=%(target)s.' %
                  {'src': remote_path, 'target': local_path})
        try:
            sftp_client.get(remote_path, local_path)
        except Exception as ex:
            LOG.error('Failed to secure copy. Reason: %s.' %
                      six.text_type(ex))
            raise SFtpExecutionError(err=ex)
985299
public function size($remoteFile)
    {
        $size = @ftp_size($this->connection, $remoteFile);

        if ($size === -1) {
            throw new Exception('Unable to get file size');
        }

        return $size;
    }
895643
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
        
        urn = Urn(file)
        urn_path = urn.path()

        remote_file_exists = self.check(urn_path)

        if not remote_file_exists:
            if 'r' in mode:
                raise RemoteResourceNotFound(urn_path)
        elif self.is_dir(urn_path):
            raise OptionNotValid(name='file', value=file)

        with tempfile.TemporaryDirectory() as temp_dir:
            local_path = f'{temp_dir}{os.path.sep}{file}'

            if remote_file_exists:
                self.download_file(file, local_path)
            else:
                if ('w' in mode or 'a' in mode or 'x' in mode) and os.path.sep in local_path:
                    os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True)

            with open(file=local_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors,
                      newline=newline, closefd=closefd, opener=opener) as f:
                yield f

            if 'w' in mode or 'a' in mode or 'x' in mode:
                self.upload_file(file, local_path)
1266460
private AFTPClient actionGetFile() throws PageException, IOException {
	required("remotefile", remotefile);
	required("localfile", localfile);

	AFTPClient client = getClient();
	Resource local = ResourceUtil.toResourceExistingParent(pageContext, localfile);// new File(localfile);
	pageContext.getConfig().getSecurityManager().checkFileLocation(local);
	if (failifexists && local.exists()) throw new ApplicationException("File [" + local + "] already exist, if you want to overwrite, set attribute failIfExists to false");
	OutputStream fos = null;
	client.setFileType(getType(local));
	boolean success = false;
	try {
	    fos = IOUtil.toBufferedOutputStream(local.getOutputStream());
	    success = client.retrieveFile(remotefile, fos);
	}
	finally {
	    IOUtil.closeEL(fos);
	    if (!success) local.delete();
	}
	writeCfftp(client);

	return client;
    }
938330
public function get($remote_file = null, $local_file = null, $mode = FTP_ASCII)
    {
        if (\ftp_get($this->_stream, $local_file, $remote_file, $mode)) {
            return true;
        }

        $this->error = 'Failed to download file "'.$remote_file.'"';

        return false;
    }
1296147
static function downloadRemoteFile($url, $destinationFilename) {
		if (!ini_get('allow_url_fopen')) {
			throw new \Exception('allow_url_fopen is disable', 501);
		}

        $message = "File was not loaded";

		if (function_exists('curl_init')) {
		    try {
                $raw = file_get_contents($url);
            } catch (\Exception $e) {
                throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST);
            }
		} else {
			$ch = curl_init($url);

			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);// таймаут4

			$response = parse_url($url);
			curl_setopt($ch, CURLOPT_REFERER, $response['scheme'] . '://' . $response['host']);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) ' .
                'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.99 YaBrowser/19.1.1.907 Yowser/2.5 Safari/537.36');


			$raw = curl_exec($ch);

            if (!$raw) {
                throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST);
            }

            curl_close($ch);
        }

        if ($raw) {
            file_put_contents($destinationFilename, $raw);
        } else {
			throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST);
		}
	}
238572
def get(remotefile, localfile = File.basename(remotefile),
	    blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      unless @binary
	gettextfile(remotefile, localfile, &block)
      else
	getbinaryfile(remotefile, localfile, blocksize, &block)
      end
    end
274892
async function download(remoteFile){
    // strip path
    let localFilename = _path.basename(remoteFile);

    // local file with same name already available ?
    if (await _fs.exists(remoteFile)){
        // change filename
        localFilename += '.' + (new Date().getTime());

        _logger.log('Local file "' + remoteFile + '" already exist - new file renamed to "' + localFilename + '"');
    }

    // try to establish a connection to the module
    await getConnection();

    _logger.log('Downloading "' + remoteFile + '" ...');

    let data = null;

    // download the file
    try{
        data = await _nodeMcuConnector.download(remoteFile);
        _logger.log('Data Transfer complete!');

    }catch(e){
        _logger.debug(e);
        throw new Error('Data Transfer FAILED!');
    }

    // store the file
    try{
        await _fs.writeFile(localFilename, data);
        _logger.log('File "' + localFilename + '" created');
    }catch(e){
        _logger.debug(e);
        throw new Error('i/o error - cannot save file');
    }
}
612529
public function get($remoteFile, $localFile)
    {
        $this->login();
        if (!isset($this->ssh)) {
            return false;
        }

        if (!$this->ssh->exec('scp -f ' . escapeshellarg($remoteFile), false)) { // -f = from
            return false;
        }

        $this->sendPacket("\0");

        if (!preg_match('#(?<perms>[^ ]+) (?<size>\d+) (?<name>.+)#', rtrim($this->receivePacket()), $info)) {
            return false;
        }

        $this->sendPacket("\0");

        $size = 0;

        $fp = null;
        if ($localFile !== false) {
            $fp = @fopen($localFile, 'wb');
            if (!$fp) {
                return false;
            }
        }

        $progressBar = new ProgressBar($this->output, $info['size']);
        $progressBar->setFormat(' %message% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
        $progressBar->start();

        $byteFormatter = new ByteFormatter();

        $content = '';
        while ($size < $info['size']) {
            $data = $this->receivePacket();
            // SCP usually seems to split stuff out into 16k chunks
            $length = strlen($data);
            $size += $length;
            $progressBar->advance($length);
            $progressBar->setMessage(
                sprintf('%s/%s', $byteFormatter->format($size), $byteFormatter->format($info['size']))
            );

            if (!$fp) {
                $content .= $data;
            } else {
                fwrite($fp, $data);
            }
        }

        $progressBar->finish();
        $this->output->writeln('');

        $this->closeChannel();

        return true;
    }
933188
public function download($local, Filesystem $remote, array $options = array())
    {
        if (!($remote instanceof File)) {
            throw new \InvalidArgumentException(sprintf(
                "Invalid remote file given, expected instance of File, got %s",
                get_class($remote)
            ));
        }

        if (true !== is_resource($local)) {
            throw new \InvalidArgumentException(sprintf(
                "Invalid local file given. Expected resource, got %s",
                gettype($local)
            ));
        }

        if (!isset($options[ FTP::NON_BLOCKING ]) || false !== $options[ FTP::NON_BLOCKING ]) {
            throw new \InvalidArgumentException("Invalid option given. Expected false as FTP::NON_BLOCKING parameter");
        }

        $defaults = array(
            FTP::TRANSFER_MODE => FTPWrapper::BINARY,
            FTP::START_POS     => 0
        );
        $options = $options + $defaults;

        return $this->wrapper->fget($local, $remote->getRealPath(), $options[ FTP::TRANSFER_MODE ], $options[ FTP::START_POS ]);
    }
89362
public InputStream getInputStream(String remotefile, long position)
			throws SftpStatusException, SshException {
		String remotePath = resolveRemotePath(remotefile);
		sftp.getAttributes(remotePath);

		return new SftpFileInputStream(sftp.openFile(remotePath,
				SftpSubsystemChannel.OPEN_READ), position);

	}
814462
def download(self, localfile: str, remotefile: str, overwrite: bool = True, **kwargs):
      
      valid = self._sb.file_info(remotefile, quiet = True)

      if valid is None:
         return {'Success' : False, 
                 'LOG'     : "File "+str(remotefile)+" does not exist."}

      if valid == {}:
         return {'Success' : False, 
                 'LOG'     : "File "+str(remotefile)+" is a directory."}

      if os.path.isdir(localfile):
         locf = localfile + os.sep + remotefile.rpartition(self._sb.hostsep)[2]
      else:
         locf = localfile

      try:
         fd = open(locf, 'wb')
      except OSError as e:
         return {'Success' : False, 
                 'LOG'     : "File "+str(locf)+" could not be opened. Error was: "+str(e)}

      port =  kwargs.get('port', 0)

      if port==0 and self.sascfg.tunnel:
         # we are using a tunnel; default to that port
         port = self.sascfg.tunnel

      try:
         sock = socks.socket()
         if self.sascfg.tunnel:
            sock.bind(('localhost', port))
         else:
            sock.bind(('', port))
         port = sock.getsockname()[1]
      except OSError:
         return {'Success' : False, 
                 'LOG'     : "Error try to open a socket in the download method. Call failed."}

      if self.sascfg.ssh:
         if not self.sascfg.tunnel:
            host = self.sascfg.hostip #socks.gethostname()
         else:
            host = 'localhost'
      else:
         host = ''

      code = """
         filename saspydir '"""+remotefile+"""' recfm=F encoding=binary lrecl=4096;
         filename sock socket '"""+host+""":"""+str(port)+"""' recfm=S encoding=binary;
         data _null_;
         file sock;
         infile saspydir;
         input;
         put _infile_;
         run;\n"""

      sock.listen(1)
      self._asubmit(code, 'text')

      datar = b''

      newsock = (0,0)
      try:
         newsock = sock.accept()
         while True:
            data = newsock[0].recv(4096)

            if len(data):
               datar += data
            else:
               if len(datar):
                  fd.write(datar)
               break
            if len(datar) > 8300:
               fd.write(datar[:8192])
               datar = datar[8192:]
      except:
         if newsock[0]:
            newsock[0].shutdown(socks.SHUT_RDWR)
            newsock[0].close()
         sock.close()
         fd.close()
         ll = self.submit("filename saspydir;", 'text')
         return {'Success' : False, 
                 'LOG'     : "Download was interupted. Returning the SAS log:\n\n"+ll['LOG']}

      newsock[0].shutdown(socks.SHUT_RDWR)
      newsock[0].close()
      sock.close()

      fd.flush()
      fd.close()

      ll = self.submit("filename saspydir;", 'text')
      return {'Success' : True, 
              'LOG'     : ll['LOG']}
1342778
def ftp_download(ftp, ftp_path, local_path):
    
    with open(local_path, 'wb') as _f:
        ftp.retrbinary('RETR %s' % ftp_path, _f.write)
1202536
public function getContent($remote_file, $mode = FTP_BINARY, $resumepos = 0)
    {
        $handle = fopen('php://temp', 'r+');

        if ($this->fget($handle, $remote_file, $mode, $resumepos)) {
            rewind($handle);
            return stream_get_contents($handle);
        }

        return null;
    }
637342
public function fget(string $remoteFile, $handle, int $resumePos = 0)
    {
        if (!@ftp_fget($this->ftp, $handle, $remoteFile, FTP_BINARY, $resumePos)) {
            throw new Exception("Cannot write in file handle");
        }

        return $this;
    }
1065545
def getbinaryfile(remotefile, localfile = File.basename(remotefile),
                      blocksize = DEFAULT_BLOCKSIZE) # :yield: data
      result = nil
      if localfile
        if @resume
          rest_offset = File.size?(localfile)
          f = open(localfile, "a")
        else
          rest_offset = nil
          f = open(localfile, "w")
        end
      elsif !block_given?
        result = ""
      end
      begin
        f.binmode if localfile
        retrbinary("RETR " + remotefile.to_s, blocksize, rest_offset) do |data|
          f.write(data) if localfile
          yield(data) if block_given?
          result.concat(data) if result
        end
        return result
      ensure
        f.close if localfile
      end
    end