简体   繁体   中英

How to transfer file from one server to another using sftp in Magento 2?

I want to transfer all the images associated to that product from M1 to M2 using sftp. I can connect to M1 using sftp. But I am not getting how to transfer it.

Here is a code to connect with sftp -

//FTP Connection
public function connectFtp($host, $user, $password, $ssl=true, $passive=true){
        return $connect = $this->sftp->open(
            array(
                'host'      =>  $host,
                'user'      =>  $user,
                'password'  =>  $password,
                'ssl'       =>  $ssl,
                'passive'   =>  $passive
            )
        );
    }

//Downlaod images from M1 and transfer to M2 temp folder
    public function downloadImages($images){
        //Connecting to M1
        $connect = $this->connectFtp(SELF::M1_HOST, SELF::M1_USERNAME, SELF::M1_PASSWORD, SELF::M1_SSL, SELF::M1_PASSIVE);
        if($connect){
           /* Code to transfer */
        }
    }

How to achieve this file transfer? As per some project requirements, we don't want to use any plugin.

Do you just want to transfer ALL the images from M1 to M2?

You can try to rsync the images across instead:

rsync user@m1.host:/path/to/copy user@m2.host:/path/to/copy

Working code for File transfer from SFTP server to Our Server.

  $sftp = $obj->create('Magento\Framework\Filesystem\Io\Sftp');
  $open =  $sftp->open(
       array(
           'host' => $sftp_hostname,
           'username' => $sftp_username,
           'password' => $sftp_password,
           'port'=>$sftp_port
       )
    );

    try{
        // Change directory and move to require directory
        $sftp->cd('/enter_your_sftp_file_path_here/');

        //Fetching/Listing all the files.
        $sftp_server_files = $sftp->ls();

        //File path to put files from SFTP Server to our local server
        $filepath = $dir->getRoot() . '/var/import/inventory/';

        foreach ($sftp_server_files as $file) {

            //Copy files from server
            $source = $file['text'];
            if(strpos($source, 'zip') !== false){
                $destination = $filepath.$source;
                $result = $sftp->read($source, $destination);
                if($result == 'true') {
                   $message[] = 'File read from SFTP server : '.$source;
                }
                else
                {
                  $message[] = 'File not able to read from SFTP server : '.$source;
                }
            }
        }
    } catch ( Exception $e) {
        echo $e->getMessage();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM