0

estoy usando la api de google para subir archivos a drive los sube correctamente en local pero en produccion solo sube los archivos ligeros.

$fileMetadata = new Google_Service_Drive_DriveFile(array('name'=> $nombre_estudio));
       // $content = file_get_contents('files/photo.jpg');
        $createdFile = $service->files->create($fileMetadata, array(
            'data' => $data,
            'mimeType' => 'application/zip',
            'uploadType' => 'Resumable',
            'fields' => 'id, webContentLink'));

acabo de cambiar 'uploadType' => 'Resumable', tenia anteriormente multipart

este codigo lo modifique por que no agregaba los archivos

function insertaArchivoDrive($service, $nombre_estudio, $folderId, $data){
        // This is uploading a file directly, with no metadata associated.
        $file = new Google_Service_Drive_DriveFile();
        $file->setName($nombre_estudio);
        $file->setDescription('A test zip');
        $file->setMimeType('application/zip');
        if(isset($folderId)){                     
            $file->setParents(array($folderId));    
        }

        /*$createdFile = $service->files->create($file, array(
              'data' => $data,
              'mimeType' => 'application/zip',
              'uploadType' => 'multipart',
              'fields' => 'id, webContentLink'
            ));

            printf("File ID: %s\n", $file->id);*/
        // echo "createdFile" . "<br/>";

        $fileMetadata = new Google_Service_Drive_DriveFile(array('name'=> $nombre_estudio));
       // $content = file_get_contents('files/photo.jpg');
        $createdFile = $service->files->create($fileMetadata, array(
            'data' => $data,
            'mimeType' => 'application/zip',
            'uploadType' => 'Resumable',
            'fields' => 'id, webContentLink'));
        //printf("File IDd: %s\n", $createdFile->id);

        return $createdFile;

    }

$file lo cambie por $fileMetadata y con esto pude agregar los archivos a drive y guardar el registro en la base de datos.

/////nuevo codigo

  function leerPorPedazos($fp, $bytesDelPedazo){
        $totalBytes = 0;
        $pedazoGigante = "";
        while (!feof($fp)) {
            $pedazo = fread($fp, 8192);
            $totalBytes += strlen($pedazo);
            $pedazoGigante .= $pedazo;
            if ($totalBytes >= $bytesDelPedazo) {
                return $pedazoGigante;
            }
        }
        return $pedazoGigante;
    }
    $archivoDrive = new Google_Service_Drive_DriveFile();
    $archivoDrive->setName($nombre_estudio);
    $archivoDrive->setDescription('A test zip');
    $archivoDrive->setMimeType('application/zip');



    $bytesDelPedazo = 1 * 1024 * 1024; //128Kbs

    $paramsOpc = array(
        'fields' => '*'
    );

    $this->client->setDefer(true);
    $solicitud = $service->files->create($archivoDrive,$paramsOpc);        
    $multimedia = new Google_Http_MediaFileUpload(
        $this->client,
        $solicitud,
        "application/zip",
        null,
        true,
        $bytesDelPedazo
    );
    $multimedia->setFileSize(filesize($ruta));

    $estado = false;
    $fp = fopen($ruta, "rb");
    while (!$estado && !feof($fp)) {
        // leemos hasta que dejamos de obtener $bytesDelPedazo del $archivoLocal
        $pedazo = leerPorPedazos($fp, $bytesDelPedazo);
        $estado = $multimedia->nextChunk($pedazo);
    }
    var_dump($archivoDrive);
    return $archivoDrive;

si lo dejo haci me inserta todos los campos excepto id de carpeta folder de la carpeta

si agrego estas dos lineas no me inserta nada en la base

$archivoDrive->setId($folderId);
    $archivoDrive->setParents(array($folderId));

esto es lo qjue me imprime archivoDrive

file_get_contents
object(Google_Service_Drive_DriveFile)#57 (64) { ["collection_key":protected]=> string(6) "spaces" ["appProperties"]=> NULL ["capabilitiesType":protected]=> string(42) "Google_Service_Drive_DriveFileCapabilities" ["capabilitiesDataType":protected]=> string(0) "" ["contentHintsType":protected]=> string(42) "Google_Service_Drive_DriveFileContentHints" ["contentHintsDataType":protected]=> string(0) "" ["createdTime"]=> NULL ["description"]=> string(10) "A test zip" ["explicitlyTrashed"]=> NULL ["fileExtension"]=> NULL ["folderColorRgb"]=> NULL ["fullFileExtension"]=> NULL ["hasAugmentedPermissions"]=> NULL ["hasThumbnail"]=> NULL ["headRevisionId"]=> NULL ["iconLink"]=> NULL ["id"]=> NULL ["imageMediaMetadataType":protected]=> string(48) "Google_Service_Drive_DriveFileImageMediaMetadata" ["imageMediaMetadataDataType":protected]=> string(0) "" ["isAppAuthorized"]=> NULL ["kind"]=> NULL ["lastModifyingUserType":protected]=> string(25) "Google_Service_Drive_User" ["lastModifyingUserDataType":protected]=> string(0) "" ["md5Checksum"]=> NULL ["mimeType"]=> string(15) "application/zip" ["modifiedByMe"]=> NULL ["modifiedByMeTime"]=> NULL ["modifiedTime"]=> NULL ["name"]=> string(19) "FiraCode-master.zip" ["originalFilename"]=> NULL ["ownedByMe"]=> NULL ["ownersType":protected]=> string(25) "Google_Service_Drive_User" ["ownersDataType":protected]=> string(5) "array" ["parents"]=> NULL ["permissionsType":protected]=> string(31) "Google_Service_Drive_Permission" ["permissionsDataType":protected]=> string(5) "array" ["properties"]=> NULL ["quotaBytesUsed"]=> NULL ["shared"]=> NULL ["sharedWithMeTime"]=> NULL ["sharingUserType":protected]=> string(25) "Google_Service_Drive_User" ["sharingUserDataType":protected]=> string(0) "" ["size"]=> NULL ["spaces"]=> NULL ["starred"]=> NULL ["teamDriveId"]=> NULL ["thumbnailLink"]=> NULL ["thumbnailVersion"]=> NULL ["trashed"]=> NULL ["trashedTime"]=> NULL ["trashingUserType":protected]=> string(25) "Google_Service_Drive_User" ["trashingUserDataType":protected]=> string(0) "" ["version"]=> NULL ["videoMediaMetadataType":protected]=> string(48) "Google_Service_Drive_DriveFileVideoMediaMetadata" ["videoMediaMetadataDataType":protected]=> string(0) "" ["viewedByMe"]=> NULL ["viewedByMeTime"]=> NULL ["viewersCanCopyContent"]=> NULL ["webContentLink"]=> NULL ["webViewLink"]=> NULL ["writersCanShare"]=> NULL ["internal_gapi_mappings":protected]=> array(0) { } ["modelData":protected]=> array(0) { } ["processed":protected]=> array(0) { } } FILEID:
9
  • ¿Cuál es el error?
    – Morfinismo
    el 10 jul. 2019 a las 11:12
  • no me genera un error el archivo no se sube a drive si es mayor a 40 megas el 10 jul. 2019 a las 15:33
  • @Morfinismo que informacion necesitas para poder ayudarme a solucionar este problema? el 10 jul. 2019 a las 17:40
  • Normalmente, siempre hay un error, pero si no hay alguno en tu caso, no queda más que intentar replicar el problema. Una duda... ¿es cuenta de consumidor de gmail o es cuenta de G Suite?
    – Morfinismo
    el 10 jul. 2019 a las 17:45
  • es de G suite estoy buscando algun error que mande en local en estos momentos si encuentro algun error aviso, tengo una teoria que el error podria ser por Resumable o multipart como mencione anteriormente solo con archivos mayor a 30 megas es donde no termina el proceso el 10 jul. 2019 a las 17:57

1 respuesta 1

1

Tu solución es buena para cargas sencillas, 10Mb o menos. Para cargas mayores a 10Mb es mejor si se hace por pedazos. No tengo mucho tiempo para explicar ahorita, pero te dejo el código. Cualquier duda, me contás en los comentarios.

<?php session_start();

//incluir la libreria del cliente de google php
require_once '../google-api-php-client-2.1.3/vendor/autoload.php';

//definir el alcance de permisos
$permisos = array('https://www.googleapis.com/auth/drive');

//crear y configurar el objeto cliente
$cliente = new Google_Client();
$cliente->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/index.php');
$cliente->setAuthConfig("ruta_a_llave.json");
$cliente->addScope($permisos);

//proceso para leer un archivo por pedazos
function leerPorPedazos($fp, $bytesDelPedazo){
    $totalBytes = 0;
    $pedazoGigante = "";
    while (!feof($fp)) {
        $pedazo = fread($fp, 8192);
        $totalBytes += strlen($pedazo);
        $pedazoGigante .= $pedazo;
        if ($totalBytes >= $bytesDelPedazo) {
            return $pedazoGigante;
        }
    }
    return $pedazoGigante;
}

if (isset($_SESSION["access_token"]) && $_SESSION["access_token"]) {

    $cliente->setAccessToken($_SESSION["access_token"]);
    $servicio = new Google_Service_Drive($cliente); // definir el serivico que se está solicitando

    $archivoLocal = "ruta/al/archivo.zip"; // definimos la ruta del archivo a cargar

    //preparar el archivo drive
    $archivoDrive = new Google_Service_Drive_DriveFile(
        array(
            'name' => 'nombre_del_archivo.zip',
            'parents' => array("1zx45Dt_z5dfer528dMg")
        )
    );
    $bytesDelPedazo = 1 * 1024 * 1024; //128Kbs

    //configurar los parámetros opcionales
    $paramsOpc = array(
        'fields' => '*'
    );

    //llamar a la api y configurar al cliente diferido para que no regrese inmediatamente
    $cliente->setDefer(true);
    $solicitud = $servicio->files->create($archivoDrive, $paramsOpc);

    //crear una carga de archivo multimedia para representar el proceso de carga
    $multimedia = new Google_Http_MediaFileUpload(
        $cliente,
        $solicitud,
        "application/zip",
        null,
        true,
        $bytesDelPedazo
    );
    $multimedia->setFileSize(filesize($archivoLocal));

    //cargamos todos los pedazos. $estado será false hasta que el proceso esté completo
    $estado = false;
    $fp = fopen($archivoLocal, "rb");
    while (!$estado && !feof($fp)) {
        // leemos hasta que dejamos de obtener $bytesDelPedazo del $archivoLocal
        $pedazo = leerPorPedazos($fp, $bytesDelPedazo);
        $estado = $multimedia->nextChunk($pedazo);
    }

    $cliente->setDefer(false);    
    //var_dump($estado);
    echo "Id del archvio: " . $estado->id;
    echo "Folder del archivo: " . $estado->parents;

} else {

    if (!isset($_GET["code"])) {

        $authUrl = $cliente->createAuthUrl();
        header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));

    } else {

        $cliente->authenticate($_GET['code']);
        $_SESSION['access_token'] = $cliente->getAccessToken();

        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

    }
}
14
  • gracias por reponder me comenta mi jefe que intente solucionar primero con el codigo que tengo antes de implementar todo , typpe=resumable e s para subir archivos con mayor peso pero no se como implementarlo. developers.google.com/drive/api/v3/manage-uploads el 15 jul. 2019 a las 22:04
  • @CarlosEnriqueGilGil Suerte entonces. La otra manera es más compleja y lástima que no tengo tiempo para escribir detalladamente la implementación. Pensé que bastaría con una solución no un requerimiento en específico de tu jefe.
    – Morfinismo
    el 15 jul. 2019 a las 22:31
  • a mi si me sirve tu solucion y te di por bien respondida la pregunta gracias pero el que manda es mi jefe y hasta que me de luz verde podre usar tu codigo gracias por ayudarme. el 15 jul. 2019 a las 23:17
  • disculpa como puedo obtener el id y el folder de drive con tu metodo el 16 jul. 2019 a las 16:20
  • ya casi queda ya guarda datos en la base de datos solo me falta el id y el folder peor creo que lo estoy haciendo mal, aqui es donde tendria que poner el folder verdad? "1zx45Dt_z5dfer528dMg" el 16 jul. 2019 a las 16:58

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.