Como permitir que usuários façam upload de arquivos
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
ID da região
O REGION_ID é um código abreviado que o Google atribui
com base na região que você selecionou ao criar o aplicativo. O código não
corresponde a um país ou estado, ainda que alguns IDs de região sejam semelhantes
aos códigos de país e estado geralmente usados. Para apps criados após
fevereiro de 2020, o REGION_ID.r está incluído nos
URLs do App Engine. Para apps existentes criados antes dessa data, o
ID da região é opcional no URL.
Ao fazer upload diretamente no Google Cloud Storage, você faz uma solicitação HTTP POST para um URL específico, que será descrito em breve. O App Engine usa um serviço de upload específico para processar a postagem e gravar o arquivo no Google Cloud Storage. Quando a gravação do arquivo é concluída, o Google App Engine notifica o aplicativo sobre o término do upload. Como seu aplicativo é invocado apenas após a conclusão, é possível usar este método para fazer upload de arquivos muito grandes, até o máximo atual de 100 terabytes.
O upload de arquivos diretamente para o Google Cloud Storage pelo usuário é mais rápido e econômico do que a gravação no Google Cloud Storage usando o aplicativo do App Engine, já que isso consome horas de instâncias e gera custos. Além disso, a gravação do arquivo não ocorre em uma solicitação para o aplicativo. Portanto, ele está isento do tempo limite da solicitação que se aplica e permite uploads de arquivos muito grandes.
Como implementar uploads de arquivos
Para implementar o upload de arquivos do usuário:
Importe CloudStorageTools:
use google\appengine\api\cloud_storage\CloudStorageTools;
Consulte opções createUploadUrl para detalhes sobre as opções disponíveis. Observe que my_bucket será YOUR_APP_ID.
REGION_ID.r.appspot.com se estiver usando o bucket padrão.
É necessário iniciar o upload desse URL dentro de 10 minutos após a criação dele. Além disso, não é possível alterar o URL, que é assinado e a assinatura é verificada antes do início do upload.
Use esse URL como a ação do formulário que você utiliza para aceitar uploads. Por exemplo:
Após o upload dos arquivos, um POST é criado para o caminho especificado como o primeiro parâmetro para createUploadUrl. No exemplo acima, é /upload_handler.php. O ambiente de execução do PHP forma o $_FILES super global correto e tmp_filename refere-se ao nome do arquivo carregado recentemente no Google Cloud Storage.
Por exemplo, suponha que o conteúdo do upload_handler.php seja o seguinte:
var_dump($_FILES);
O upload de um arquivo chamado hello.txt pode resultar na seguinte saída:
Após a conclusão do upload, leia o arquivo enviado usando o wrapper de stream gs://. Você usa move_uploaded_file como faria normalmente para qualquer outro arquivo enviado, por exemplo:
As opções de createUploadUrl válidas são mostradas na seguinte tabela:
Opção
Descrição
max_bytes_per_blob
Número inteiro. Valor padrão: unlimited. O valor do maior tamanho permitido para um blob enviado.
max_bytes_total
Número inteiro. Valor padrão: unlimited. O tamanho total de todos os blobs enviados.
gs_bucket_name
String. O nome de um bucket do Google Cloud Storage ao qual os blobs devem ser enviados. Se você não especificar um valor, o upload do blob será feito para o intervalo padrão do aplicativo.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-19 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:"]]