File Download

@param string $remotePath
@param string $localPath
@param string $type = 'ascii'

@return bool
970808
public function download(String $remotePath, String $localPath, String $type = 'ascii') : Bool
    {
        if( ftp_get($this->connect, $localPath, $remotePath, Helper::toConstant($type, 'FTP_')) )
        {
            return true;
        }
        else
        {
            throw new FileRemoteDownloadException($localPath);
        }
    }
862954
private String localFilePath(File downloadDirectory) throws MojoFailureException {
        if (downloadDirectory.exists()) {
            if (downloadDirectory.isDirectory()) {
                return downloadDirectory.getAbsolutePath();
            } else {
                throw new MojoFailureException("'" + downloadDirectory.getAbsolutePath() + "' is not a directory!");
            }
        }

        if (downloadDirectory.mkdirs()) {
            return downloadDirectory.getAbsolutePath();
        } else {
            throw new MojoFailureException("Unable to create download directory!");
        }
    }
1188379
def download(self, local, remote):
        
        self.sync(RemoteFile(remote, self.api), LocalFile(local))
1250749
public void copyFrom(String remotePath, String localPath) throws Exception {
        FileOutputStream fos = null;
        String rfile = remotePath;
        String lfile = localPath;

        // If localPath is a directory, create it if it does not exist
        String prefix = null;
        File local = new File(lfile);
        if (!local.exists()) {
            local.mkdir();
            prefix = lfile + File.separator;
        } else {
            if (local.isDirectory()) {
                prefix = lfile + File.separator;
            }
        }

        // exec 'scp -f rfile' remotely
        String command = "scp -f " + remotePath;
        Channel channel = this.session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);

        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] buf = new byte[1024];

        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();

        while (true) {
            int c = checkAck(in);
            if (c != 'C') {
                break;
            }

            // read '0644 '
            in.read(buf, 0, 5);

            long filesize = 0L;
            while (true) {
                if (in.read(buf, 0, 1) < 0) {
                    // error
                    break;
                }
                if (buf[0] == ' ') {
                    break;
                }
                filesize = filesize * 10L + (long) (buf[0] - '0');
            }

            String file = null;
            for (int i = 0;; i++) {
                in.read(buf, i, 1);
                if (buf[i] == (byte) 0x0a) {
                    file = new String(buf, 0, i);
                    break;
                }
            }

            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();

            // read a content of lfile
            fos = new FileOutputStream(prefix == null ? lfile : prefix + file);
            int foo;
            while (true) {
                if (buf.length < filesize) {
                    foo = buf.length;
                } else {
                    foo = (int) filesize;
                }
                foo = in.read(buf, 0, foo);
                if (foo < 0) {
                    // error
                    break;
                }
                fos.write(buf, 0, foo);
                filesize -= foo;
                if (filesize == 0L) {
                    break;
                }
            }
            fos.close();
            fos = null;

            if (checkAck(in) != 0) {
                throw new RuntimeException("Read error on inputstream");
            }

            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
        }
        channel.disconnect();
    }
1224146
function GetLastModifiedDate($remotepath) 
	{
		$curl = curl_init($remotepath);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ET_Util::shouldVerifySslPeer($this->sslVerifyPeer));
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_FILETIME, true);

		if (!empty($this->proxyHost)) {
			curl_setopt($curl, CURLOPT_PROXY, $this->proxyHost);
		}
		if (!empty($this->proxyPort)) {
			curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxyPort);
		}
		if (!empty($this->proxyUserName) && !empty($this->proxyPassword)) {
			curl_setopt($curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
			curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxyUserName.':'.$this->proxyPassword);
		}

		$result = curl_exec($curl);
		
		if ($result === false) {
			throw new Exception(curl_error($curl)); 
		}
		
		return curl_getinfo($curl, CURLINFO_FILETIME);
	}
1100736
def download_file(self, remote, local):
        
        file = open(local, 'wb')
        try:
            self.download(remote, file)
        finally:
            file.close()
1087747
def download(self, localfile: str, remotefile: str, overwrite: bool = True, **kwargs):
      
      logf     = ''
      logn     = self._logcnt()
      logcodei = "%put E3969440A681A24088859985" + logn + ";"
      logcodeo = "\nE3969440A681A24088859985" + logn
      logcodeb = logcodeo.encode()

      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')
         fd.write(b'write can fail even if open worked, as it turns out')
         fd.close()
         fd = open(locf, 'wb')
      except OSError as e:
         return {'Success' : False, 
                 'LOG'     : "File "+str(locf)+" could not be opened or written to. Error was: "+str(e)}

      code = "filename _sp_updn '"+remotefile+"' recfm=F encoding=binary lrecl=4096;"

      ll = self.submit(code, "text")
      logf  = ll['LOG']

      self.stdin[0].send(b'tom says EOL=DNLOAD                          \n')
      self.stdin[0].send(b'\n'+logcodei.encode()+b'\n'+b'tom says EOL='+logcodeb+b'\n')

      done  = False
      datar = b''
      bail  = False

      while not done:
         while True:
             if os.name == 'nt':
                try:
                   rc = self.pid.wait(0)
                   self.pid = None
                   self._sb.SASpid = None
                   return {'Success' : False, 
                           'LOG'     : "SAS process has terminated unexpectedly. RC from wait was: "+str(rc)}
                except:
                   pass
             else:
                rc = os.waitpid(self.pid, os.WNOHANG)
                if rc[1]:
                    self.pid = None
                    self._sb.SASpid = None
                    return {'Success' : False, 
                            'LOG'     : "SAS process has terminated unexpectedly. RC from wait was: "+str(rc)}

             if bail:
                if datar.count(logcodeb) >= 1:
                   break
             try:
                data = self.stdout[0].recv(4096)
             except (BlockingIOError):
                data = b''

             if len(data) > 0:
                datar += data
                if len(datar) > 8300:
                   fd.write(datar[:8192])
                   datar = datar[8192:]
             else:
                sleep(0.1)
                try:
                   log = self.stderr[0].recv(4096).decode(self.sascfg.encoding, errors='replace')
                except (BlockingIOError):
                   log = b''

                if len(log) > 0:
                   logf += log
                   if logf.count(logcodeo) >= 1:
                      bail = True
         done = True

      fd.write(datar.rpartition(logcodeb)[0])
      fd.flush()
      fd.close()

      self._log += logf
      final = logf.partition(logcodei)
      z = final[0].rpartition(chr(10))
      prev = '%08d' %  (self._log_cnt - 1)
      zz = z[0].rpartition("\nE3969440A681A24088859985" + prev +'\n')
      logd = zz[2].replace(";*\';*\";*/;", '')

      ll = self.submit("filename _sp_updn;", 'text')
      logd += ll['LOG']
      
      return {'Success' : True, 
              'LOG'     : logd}
300501
public function putFile($path, $localFilePath, Config $config)
    {
        $object = $this->applyPathPrefix($path);
        $options = $this->getOptionsFromConfig($config);

        $options[OssClient::OSS_CHECK_MD5] = true;

        if (! isset($options[OssClient::OSS_CONTENT_TYPE])) {
            $options[OssClient::OSS_CONTENT_TYPE] = Util::guessMimeType($path, '');
        }

        try {
            $this->client->uploadFile($this->bucket, $object, $localFilePath, $options);
        } catch (OssException $e) {
            return false;
        }

        $type = 'file';
        $result = compact('type', 'path');
        $result['mimetype'] = $options[OssClient::OSS_CONTENT_TYPE];

        return $result;
    }
934644
@Given("^I inbound copy '(.+?)' through a ssh connection to '(.+?)'$")
    public void copyFromRemoteFile(String remotePath, String localPath) throws Exception {
        commonspec.getRemoteSSHConnection().copyFrom(remotePath, localPath);
    }
356767
function download( $url, $local, $headers = array(), $verifyssl = null ) {
		global $argv;

		$out = fopen( $local, 'wb' );

		if( is_string( $headers ) ) curl_setopt( $this->curl_instance, CURLOPT_HTTPHEADER, array( $headers ) );
		else $this->setCurlHeaders( $headers );
		$this->setVerifySSL( $verifyssl );

		// curl_setopt($this->curl_instance, CURLOPT_FILE, $out);
		curl_setopt( $this->curl_instance, CURLOPT_HTTPGET, 1 );
		curl_setopt( $this->curl_instance, CURLOPT_POST, 0 );
		curl_setopt( $this->curl_instance, CURLOPT_URL, $url );
		curl_setopt( $this->curl_instance, CURLOPT_HEADER, 0 );

		if( ( !is_null( $argv ) && in_array( 'peachyecho', $argv ) ) || $this->echo ) {
			pecho( "DLOAD: $url\n", PECHO_NORMAL );
		}

		Hooks::runHook( 'HTTPDownload', array( &$this, &$url, &$local ) );

		fwrite( $out, $this->doCurlExecWithRetrys() );
		fclose( $out );

		return true;

	}
593849
public function readFromLocalImage($localImage, $remoteFolder, $barcodeReadType)
    {
        $folder = new Folder();
        $folder->UploadFile($localImage, $remoteFolder);
        $data = $this->ReadR(basename($localImage), $remoteFolder, $barcodeReadType);
        return $data;
    }
299703
def upload(self, localpath, href):
        
        localpath = _(localpath)
        href = remote(href)
        if not os.path.exists(localpath):
            logger.info(u("ERROR: localfile: %s not found") % localpath)
            return
        if os.path.islink(localpath):
            return self.upload(os.path.abspath(os.path.realpath(localpath)), href)
            # 3 tryings to upload file
        for iTry in range(TRYINGS):
            try:
                logger.info(u("upload: %s %s") % (localpath, href))
                length = os.path.getsize(localpath)

                if PY3:
                    _open = open(_encode_utf8(localpath), "r", encoding='latin-1')
                else:
                    _open = open(_encode_utf8(localpath), "r")
                with _open as f:
                    return self.write(f, href, length=length)
            except ConnectionException:
                raise
            except Exception:
                e = sys.exc_info()[1]
                logger.exception(e)
130858
public function getFile($remote, $local)
    {
        return ftp_get($this->connection, $local, $remote, $this->getTransferenceEncoding($remote));
    }
642400
public function get($local, $remote)
	{
		// Determine file type
		$mode = $this->_findMode($remote);

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				Log::add(__METHOD__ . ': Unable to use passive mode.', Log::WARNING, 'jerror');

				return false;
			}

			if (@ftp_get($this->conn, $local, $remote, $mode) === false)
			{
				Log::add(__METHOD__ . 'Bad response.', Log::WARNING, 'jerror');

				return false;
			}

			return true;
		}

		$this->_mode($mode);

		// Check to see if the local file can be opened for writing
		$fp = fopen($local, "wb");

		if (!$fp)
		{
			Log::add(sprintf('%1$s: Unable to open local file for writing.  Local path: %2$s', __METHOD__, $local), Log::WARNING, 'jerror');

			return false;
		}

		// Start passive mode
		if (!$this->_passive())
		{
			Log::add(__METHOD__ . ': Unable to use passive mode.', Log::WARNING, 'jerror');

			return false;
		}

		if (!$this->_putCmd('RETR ' . $remote, array(150, 125)))
		{
			@ fclose($this->dataconn);
			Log::add(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150 or 125].  Path sent: %3$s', __METHOD__, $this->response, $remote),
				Log::WARNING, 'jerror'
			);

			return false;
		}

		// Read data from data port connection and add to the buffer
		while (!feof($this->dataconn))
		{
			$buffer = fread($this->dataconn, 4096);
			fwrite($fp, $buffer, 4096);
		}

		// Close the data port connection and file pointer
		fclose($this->dataconn);
		fclose($fp);

		if (!$this->_verifyResponse(226))
		{
			Log::add(
				sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected: 226].  Path sent: %3$s', __METHOD__, $this->response, $remote),
				Log::WARNING, 'jerror'
			);

			return false;
		}

		return true;
	}
1315812
public function put($localFile = null, $remoteFile = null, $mode = FTP_ASCII)
        {
            // attempt to upload file
            if(ftp_put(static::$_stream, $remoteFile, $localFile, $mode)) {
                // success
                return true;
            // upload failed
            } else {
                static::$error = "Failed to upload file \"{$localFile}\"";
                return false;
            }
        }
31550
protected function upload($local_file)
    {
        if (!is_file($local_file)) {
            throw new WebDriverException('You may only upload files: ' . $local_file);
        }

        // Create a temporary file in the system temp directory.
        $temp_zip = tempnam(sys_get_temp_dir(), 'WebDriverZip');
        $zip = new ZipArchive();
        if ($zip->open($temp_zip, ZipArchive::CREATE) !== true) {
            return false;
        }
        $info = pathinfo($local_file);
        $file_name = $info['basename'];
        $zip->addFile($local_file, $file_name);
        $zip->close();
        $params = [
            'file' => base64_encode(file_get_contents($temp_zip)),
        ];
        $remote_path = $this->executor->execute(
            DriverCommand::UPLOAD_FILE,
            $params
        );
        unlink($temp_zip);

        return $remote_path;
    }
435999
public function checkRequest($type, $file)
    {
        // no checks for getters
        if(in_array($type, ['detectors', 'mime-types', 'parsers', 'version']))
        {
            //
        }
        // invalid local file
        elseif(!preg_match('/^http/', $file) && !file_exists($file))
        {
            throw new Exception("File $file can't be opened");
        }
        // invalid remote file
        elseif(preg_match('/^http/', $file) && !preg_match('/200/', get_headers($file)[0]))
        {
            throw new Exception("File $file can't be opened", 2);
        }
        // download remote file if required only for integrated downloader
        elseif(preg_match('/^http/', $file) && $this->downloadRemote)
        {
            $file = $this->downloadFile($file);
        }

        return $file;
    }