如何使用PHP将文件从谷歌驱动器复制到另一台服务器

时间:2015-09-11 13:41:48

标签: javascript php google-drive-api google-picker

我想使用php将文件从谷歌驱动器复制到另一台服务器。

我使用了谷歌驱动器选择器,当用户点击我以前获取下载URL的任何文件时,我认为它可以通过复制功能完成,但它没有用。

任何解决方案请。

function getDownloadurl(fileId) {
           var request =  gapi.client.request({
                    'path': '/drive/v2/files/' + fileId,
                    'params': { 'maxResults': '1000' },
                    callback: function (responsejs, responsetxt) {
                    var fileDownloadUrl = responsejs.downloadUrl; 
              $.ajax({
                type: "POST",
                url: "ajax-files/copy_drive_file.php",
                data: { gd_url:fileDownloadUrl },
                async:false,
                success: function(data)
                {   

                }
});

copy_drive_file.php

$sourcePath=$_POST['gd_url'];
copy($sourcePath, 'sss/file.jpg'); 

2 个答案:

答案 0 :(得分:2)

您需要在从PHP获取时授权和验证您的请求

YourJsFile

function getDownloadurl(fileId) {
var accessToken =  gapi.auth.getToken().access_token;
var request = gapi.client.request({
            'path': '/drive/v2/files/' + fileId,
            'params': {
                'maxResults': '1000'
            },
            callback: function(responsejs, responsetxt) {
                var fileDownloadUrl = responsejs.downloadUrl;
                $.ajax({
                    type: "POST",
                    url: "ajax-files/copy_drive_file.php",
                    data: {
                        gd_url: fileDownloadUrl,
                        accessToken: accessToken
                    },
                    async: false,
                    success: function(data) {
                        console.log(data);
                    }
                });
            }
       });
} 

<强> copy_drive_file.php

if ( isset($_POST['gd_url']) && isset($_POST['accessToken'])) {
    $url = $_POST['gd_url'];
    $accessToken = $_POST['accessToken'];
    $opts = array(
            'http'=>array(
            'method'=>"GET",
            'header' => "Authorization: Bearer " . $accessToken                 
            )
    );
    $context = stream_context_create($opts);
    $content = file_get_contents($url, false, $context);
    if (!empty($content)){
        file_put_contents("path/filename.file_extension",$content);
        echo json_encode(array('file_name' => "filename.file_extension"));
    }
}

答案 1 :(得分:0)

也许这会有所帮助?

function copyFile($service, $originFileId, $copyTitle) {
      $copiedFile = new Google_Service_Drive_DriveFile();
      $copiedFile->setTitle($copyTitle);
      try {
        return $service->files->copy($originFileId, $copiedFile);
      } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
      }
      return NULL;
    }