duanlaican1849 2017-07-28 13:42
浏览 49
已采纳

Google Api for PHP(Drive API)导出为.pdf上传的.docx文件

I cannot obtain stable script when I try upload docx file to Google Drive, and then download that file but as PDF.

Code:

//Google API
require_once('vendor/autoload.php');

putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/2ab4ece19bd5.json');
$client = new Google_Client();
$client->setApplicationName('sp-gen');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->useApplicationDefaultCredentials();
$service = new Google_Service_Drive($client);

$fileMetadata = new Google_Service_Drive_DriveFile(array(
  'name' => '281e2399740c88957143507721bd0f25.docx',
  'mimeType' => 'application/vnd.google-apps.document'
  ));

$content = file_get_contents('281e2399740c88957143507721bd0f25.docx');

$file = $service->files->create($fileMetadata, array(
  'data' => $content,
  'mimeType' => 'application/vnd.google-apps.document',
  'uploadType' => 'multipart',
  'fields' => 'id')
);

$content = $service->files->export($file->id, 'application/pdf', array( 'alt' => 'media' ));
file_put_contents(str_replace('.docx', '.pdf', '281e2399740c88957143507721bd0f25.docx'), $content->getBody()->getContents());

This code works in.. 20-30% of uses. Sometimes, $service->files->export() return error code 500 but in many cases request return normal response (200) but with Content-Length 0.

Am I doing something wrong? Or should I do some kind of loop, that try download file until success?

  • 写回答

1条回答 默认 最新

  • douling1936 2017-07-31 12:05
    关注

    OK. So I spend two days looking for solution and I came up with several conclusions:

    1. Using Server-to-Server authentication, you must create service account, with is "separate" google drive account. That's means that if you create file via script, file is created on service account, and you can access this file only via API.
    2. You can assign permissions to created file, that connect your real google account to file, and than you can access that file via Google Drive. You can not transfer ownership to file from service account to google account, because Google PHP API at this moment do not have proper method. Or I do not see way to setup this. Class summary.

    3. Key is to use Exponential backoff. In other words try unless success. ( ͡° ͜ʖ ͡°)

    CODE:

    //Google API
    require_once('vendor/autoload.php');
    
    putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/2ab4ece19bd5.json');
    $client = new Google_Client();
    $client->setApplicationName('sp-gen');
    $client->setScopes(array('https://www.googleapis.com/auth/drive'));
    $client->useApplicationDefaultCredentials();
    $service = new Google_Service_Drive($client);
    
    $fileMetadata = new Google_Service_Drive_DriveFile(array(
      'name' => '281e2399740c88957143507721bd0f25.docx',
      'mimeType' => 'application/vnd.google-apps.document'
      ));
    
    $content = file_get_contents('281e2399740c88957143507721bd0f25.docx');
    
    $file = $service->files->create($fileMetadata, array(
      'data' => $content,
      'uploadType' => 'multipart'
    );
    
    //Create new permission
    $newPermission = new Google_Service_Drive_Permission();
    
    //set email of account, that will have access to file.
    $newPermission->setEmailAddress('<email here>');
    
    //Must be user or group, if you pass email adress
    // user | group | domain | anyone
    $newPermission->setType('user');
    
    //Could be owner but I can not set transferOwnership 
    // organizer | owner | reader | writer
    $newPermission->setRole('writer');
    
    $service->permissions->create($file->getId(), $newPermission);
    
    $file_name = str_replace('.docx', '.pdf', '281e2399740c88957143507721bd0f25.docx');
    
    $attempt = 1;
    do{
      //Wait 5000ms
      usleep(500000*$attempt);
    
      //Try to get pdf file.
      $content = $service->files->export($file->getId(), 'application/pdf', array( 'alt' => 'media' ));
    
      //Save just fetched data.
      file_put_contents($file_name, $content->getBody()->getContents());
    
      if(filesize($file_name)) break;
      else $attempt++;
    
    }while(true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)