Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
ID de región
REGION_ID es un código abreviado que Google asigna en función de la región que eliges cuando creas la app. El código no corresponde a un país ni a una provincia, aunque algunos ID de región puedan parecer similares a los códigos de país y provincia que se suelen usar. En el caso de las apps creadas después de febrero de 2020, REGION_ID.r se incluye en las URL de App Engine. En el caso de las apps existentes creadas antes de esta fecha, el ID de región es opcional en la URL.
Cuando subes archivos directo a Google Cloud Storage, creas una HTTP POST en una URL específica (lo explicaremos en breve). Luego, App Engine usa un servicio de cargas específico para manejar la publicación y escribir el archivo en Google Cloud Storage. Cuando finaliza la escritura del archivo, App Engine notifica a tu aplicación que ya se realizó la carga. Dado que solo se invoca a la aplicación una vez que se completa la carga, puedes usar este método para subir archivos muy grandes (hasta el máximo actual de 100 terabytes).
Es más rápido y rentable que los usuarios suban los archivos directo a Google Cloud Storage que escribir a Google Cloud Storage desde tu aplicación de App Engine, ya que esto consume horas de instancia y genera un costo. Además, el archivo no se escribe con una solicitud a la aplicación. Por lo tanto, está exento del tiempo de espera de la solicitud que, de lo contrario, se aplicaría y permite subir archivos muy grandes.
Implementa cargas de archivos
Para implementar la carga de archivos por parte de los usuarios, haz lo siguiente:
Importa CloudStorageTools:
use google\appengine\api\cloud_storage\CloudStorageTools;
Crea la URL de carga específica de la aplicación con el método CloudStorageTools::createUploadUrl() en tu archivo .php, como se muestra a continuación:
Para obtener más detalles sobre las opciones disponibles, consulta las opciones decreateUploadUrl. Ten en cuenta que my_bucket será YOUR_APP_ID.
REGION_ID.r.appspot.com si usas el bucket predeterminado.
Recuerda que debes empezar a subir archivos a esta URL dentro de los 10 minutos posteriores a su creación. Además, no puedes modificar la URL en absoluto, ya que está firmada y la firma se verifica antes de que comience la carga.
Usa esta URL como la acción para el formulario que usas cuando aceptas cargas, por ejemplo:
Una vez que se suben los archivos, se crea un POST a la ruta que se especificó como el primer parámetro de createUploadUrl; en el ejemplo anterior, es /upload_handler.php. El entorno de ejecución del PHP crea los $_FILES correctos súper globales y tmp_filename se refiere al nombre del archivo recién subido a Google Cloud Storage.
Por ejemplo, supongamos que el contenido de upload_handler.php es el siguiente:
var_dump($_FILES);
Si subes un archivo llamado hello.txt, puede que se muestre el siguiente resultado:
Una vez que se completa la carga, puedes leer el archivo que se subió con el wrapper de transmisión gs://. Usa move_uploaded_file como harías con cualquier otro archivo subido, por ejemplo:
Las opciones de createUploadUrl se muestran en la siguiente tabla:
Opción
Descripción
max_bytes_per_blob
Número entero. Valor predeterminado: unlimited. Es el valor del mayor tamaño de BLOB que se puede subir.
max_bytes_total
Número entero. Valor predeterminado: unlimited. Es el tamaño total de los BLOB que se subieron.
gs_bucket_name
String. Es el nombre del bucket de Google Cloud Storage al que deberían subirse los BLOB. Si no especificas un valor, el BLOB se sube al bucket predeterminado de la aplicación.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eThe \u003ccode\u003eREGION_ID\u003c/code\u003e is a Google-assigned code based on the region selected during app creation, which is included in App Engine URLs for apps created after February 2020, and it does not directly correspond to a country or province.\u003c/p\u003e\n"],["\u003cp\u003eUploading files directly to Google Cloud Storage via HTTP POST is faster and more cost-effective than writing to it from the App Engine app because it avoids instance hour consumption and request timeouts, supporting files up to 100 Terabytes.\u003c/p\u003e\n"],["\u003cp\u003eTo implement user file uploads, you must import \u003ccode\u003eCloudStorageTools\u003c/code\u003e and use the \u003ccode\u003eCloudStorageTools::createUploadUrl()\u003c/code\u003e method to generate a unique upload URL that must be used within 10 minutes.\u003c/p\u003e\n"],["\u003cp\u003eUpon successful file upload, a POST request is sent to the specified handler, and the PHP runtime populates the \u003ccode\u003e$_FILES\u003c/code\u003e array, with \u003ccode\u003etmp_filename\u003c/code\u003e pointing to the uploaded file's location in Google Cloud Storage.\u003c/p\u003e\n"],["\u003cp\u003eFiles that are not moved using \u003ccode\u003emove_uploaded_file\u003c/code\u003e or \u003ccode\u003erename\u003c/code\u003e before the request finishes will be automatically removed from Google Cloud Storage.\u003c/p\u003e\n"]]],[],null,["# Allowing Users to Upload Files\n\n### Region ID\n\nThe \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e is an abbreviated code that Google assigns\nbased on the region you select when you create your app. The code does not\ncorrespond to a country or province, even though some region IDs may appear\nsimilar to commonly used country and province codes. For apps created after\nFebruary 2020, \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e`.r` is included in\nApp Engine URLs. For existing apps created before this date, the\nregion ID is optional in the URL.\n\nLearn more\n[about region IDs](/appengine/docs/legacy/standard/php/how-requests-are-routed#region-id). \nOK\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| php-gen2\n|\n| /services/access). If you are updating to the App Engine PHP 7/8 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/php-differences) to learn about your migration options for legacy bundled services.\n\n\u003cbr /\u003e\n\nWhen you upload directly to Google Cloud Storage, you make an HTTP POST to a specific URL, which we'll\ndescribe in a moment. App Engine then uses a specific *upload service* to handle\nthe post and write the file to Google Cloud Storage. When the file write is complete, App Engine\nnotifies your app that the upload is complete. Because your app is invoked only\nupon completion, you can use this method to upload very large files, up to\nthe current maximum of 100 Terabytes.\n\nUser upload of files directly to Google Cloud Storage is faster and more cost-effective than\n[writing to Google Cloud Storage](/appengine/docs/legacy/standard/php/googlestorage#writing_files_from_your_app)\nfrom your App Engine app, because this consumes instance hours and incurs cost. Moreover, the file\nwrite does not occur within a request to the application. Therefore it is exempt\nfrom the [request timeout](/appengine/docs/legacy/standard/php/how-instances-are-managed#timeout)\nthat would otherwise apply and allows uploads of very large files.\n| **Note:** Starting from version 1.9.18, you can also upload files directly to your POST handler as long as the combined size is less than 32MB. See [this page](https://gae-php-tips.appspot.com/2015/03/09/direct-file-uploads-for-php-5-5/) for more details.\n\nImplementing file uploads\n-------------------------\n\nTo implement user file upload:\n\n1. Import `CloudStorageTools`:\n\n use google\\appengine\\api\\cloud_storage\\CloudStorageTools;\n\n2. Create the application specific upload URL, using the method\n [CloudStorageTools::createUploadUrl()](/appengine/docs/legacy/standard/php/refdocs/classes/google.appengine.api.cloud_storage.CloudStorageTools#method_createUploadUrl)\n in your `.php` file as follows:\n\n $options = ['gs_bucket_name' =\u003e $my_bucket];\n $upload_url = CloudStorageTools::createUploadUrl('/upload/handler', $options);\n\n See [`createUploadUrl` options](#createuploadurl_options) for details about\n available options. Note that `my_bucket` will be\n `YOUR_APP_ID`.\n \u003cvar translate=\"no\"\u003e\u003ca href=\"#appengine-urls\" style=\"border-bottom: 1px dotted #999\" class=\"devsite-dialog-button\" data-modal-dialog-id=\"regional_url\" track-type=\"progressiveHelp\" track-name=\"modalHelp\" track-metadata-goal=\"regionalURL\"\u003eREGION_ID\u003c/a\u003e\u003c/var\u003e`.r.appspot.com` if using the default bucket.\n3. Note that you must start uploading to this URL within 10 minutes of its\n creation. Also, you cannot change the URL in any way - it is signed and the\n signature is checked before your upload begins.\n\n4. Use this URL as the action for the form you use to accept uploads, for example:\n\n \u003cform action=\"{{ upload_url }}\" enctype=\"multipart/form-data\" method=\"post\"\u003e\n Files to upload: \u003cbr\u003e\n \u003cinput type=\"file\" name=\"uploaded_files\" size=\"40\"\u003e\n \u003cinput type=\"submit\" value=\"Send\"\u003e\n \u003c/form\u003e\n\nAfter the file(s) upload, a POST is made to the path specified as the first\nparameter to `createUploadUrl`; in the example above, this is\n`/upload_handler.php`. The PHP runtime forms the correct `$_FILES` super global,\nand `tmp_filename` refers to the filename of the newly uploaded file in Google Cloud Storage.\n\nFor example, suppose the content of upload_handler.php is the following: \n\n var_dump($_FILES);\n\nUploading a file called `hello.txt` might result in the following output: \n\n array(1) {\n ['uploaded_files']=\u003e\n array(5) {\n ['name']=\u003e string(14) 'hello.txt'\n ['type']=\u003e string(10) 'text/plain'\n ['tmp_name']=\u003e string(73) 'gs://my_bucket/L2FwcHMtdXBsb2FkL2Jsb2JzL2IxNUFBVGNJNXNTd0VqR0tFSUtDRGxadGc'\n ['error']=\u003e int(0)\n ['size']=\u003e int(1452)\n }\n }\n\nAfter the upload is complete, you can read the uploaded file using the\n`gs://` stream wrapper. You use `move_uploaded_file` like you normally would for\nany other uploaded file, for example: \n\n $file_name = $_FILES['uploaded_files']['name'];\n $temp_name = $_FILES['uploaded_files']['tmp_name'];\n move_uploaded_file($temp_name, \"gs://${my_bucket}/${file_name}.txt\");\n\n| **Note:** Any user uploaded files that are not moved using `move_uploaded_file` or `rename` before the request finishes will be automatically removed from Google Cloud Storage.\n\n`createUploadUrl` options\n-------------------------\n\nValid `createUploadUrl` options are shown in the following table:"]]