POST Object

Uploads objects by using HTML forms. The uploaded object overwrites any existing object with the same name. For tips on uploading to Cloud Storage, see best practices.

Unless you need to use HTML forms (usually through a web browser) to upload objects, we strongly recommend using PUT object instead of POST.

For information about POST Object requests using the legacy signing process, see POST Object with the V2 signing process.

Query string parameters

This request does not include query string parameters.

Form fields

Field Description Required
acl The predefined ACL that you want to apply to the object that is being uploaded. If you do not specify this field the bucket's default ACL is applied. No
bucket The name of the bucket that you want to upload to. If you include this field, it must match the bucket name you specify in the action attribute. No
Cache-Control The cache control for the object. You can only set cache control for an object that is accessible to all users. For instance, an object's ACL must be public-read or public-read-write to be able to set the cache-control. No
Content-Disposition Specifies how the object data should be transmitted. For example, a Content-Disposition value of inline means that the object should be displayed immediately. No
Content-Encoding The compression algorithm for the object, such as gzip. No
Content-Length The size of the uploaded file, in bytes. No
Content-Type The MIME type of the file you are uploading via the form. If you do not specify a content type, the Cloud Storage system defaults to application/octet-stream when it serves the content. No
Expires An ISO8601 timestamp that specifies the date and time before an object is considered stale by the browser. No
file The file you are uploading. Must be the last field in the form. You can upload only one object per request. Yes
key The name of the object that you are uploading. You can also use the ${filename} variable if a user is providing a file name. Yes
policy

The security policy that describes what can and cannot be uploaded in the form. The policy document must be Base64 encoded. See policy documents for more information.

*If you do not provide a security policy, requests are considered to be anonymous and will only work with buckets that have granted WRITE or FULL_CONTROL permission to anonymous users.

No*
success_action_redirect A URL that users are redirected to when an upload is successful. If you do not provide a URL, Cloud Storage responds with the status code that you specified in success_action_status. No
success_action_status The status code that you want Cloud Storage to respond with when an upload is successful. The default is 204, but you can change this to 200 or 201. If you choose 200 or 204, Cloud Storage returns an empty document with those status codes. If you choose 201, Cloud Storage returns an XML document with the elements that are described in Response Body Elements. Note: The Adobe Flash player might not handle responses with an empty document body. You should use status code 201 if this is the case. No
x-goog-algorithm The signing algorithm used to create the signature associated with your policy document. Possible values are GOOG4-HMAC-SHA256 and GOOG4-RSA-SHA256 Only if you specify a policy
x-goog-credential The credentials used to create the signature associated with your policy document. x-goog-credential has the form AccessKeyId/CredentialScope, where:
  • AccessKeyId is the email address of the entity responsible for creating the signature. This entity is typically a service account, but may also be a user account.
  • CredentialScope is the credential scope used in the signature.
Only if you specify a policy
x-goog-date The current date, in the ISO 8601 basic format YYYYMMDD'T'HHMMSS'Z'. Only if you specify a policy
x-goog-signature The signature associated with your policy document. Only if you specify a policy
x-goog-meta-* A field for custom metadata. You can use this to specify any additional metadata that is not provided by the other form fields. For example, x-goog-meta-reviewer: jane or x-goog-meta-project-manager: john is custom metadata. No

Response body elements

The following response body elements are returned in an XML document only if you set success_action_status to 201.

Element Description
Bucket Bucket in which the object was stored.
ETag HTTP 1.1 entity tag for the object.
Key The object's name.
Location The URI for the object.

Usage and examples

The form must be UTF-8 encoded. You can specify form encoding in the form's HTML head tag or by using the Content-Type request header.

Your form tag must specify the following three items:

  • An action.

    The action attribute specifies an XML API request endpoint. Valid endpoints include https://[BUCKET_NAME].storage.googleapis.com, https://storage.googleapis.com/[BUCKET_NAME], and CNAME redirects.

  • A method.

    The method attribute specifies the method that you are using to submit the form. It must be post.

  • An enclosure type.

    The enctype attribute specifies the enclosure type you are using and must always be multipart/form-data.

The following is an example HTML form using a policy document:

HTML

<form action="https://storage.googleapis.com/travel-maps" method="post" enctype="multipart/form-data">
<input type="text" name="key" value="test-object">
<input type="hidden" name="Content-Type" value="image/jpeg">
<input type="hidden" name="success_action_redirect" value="https://www.example.com/success_notification.html">
<input type="hidden" name="policy" value="eyJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJ0cmF2ZWwtbWFwcyJ9LHsiY29udGVudC10eXBlIjoiaW1hZ2UvanBlZyJ9LHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiJodHRwOi8vd3d3LmV4YW1wbGUuY29tL3N1Y2Nlc3Nfbm90aWZpY2F0aW9uLmh0bWwifSx7ImtleSI6InRlc3Qtb2JqZWN0In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoiZXhhbXBsZV9hY2NvdW50QGV4YW1wbGVfcHJvamVjdC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDE5MTEwMi9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9">
<input type="hidden" name="x-goog-algorithm" value="GOOG4-RSA-SHA256">
<input type="hidden" name="x-goog-credential" value="example_account@example_project.iam.gserviceaccount.com/20191102/auto/storage/goog4_request">
<input type="hidden" name="x-goog-date" value="20191102T043530Z">
<input type="hidden" name="x-goog-signature" value="58bc39b8f604ee1f18171fee4828ef8967f3d2721676570e115d68c2f133820cbb833976f18955516b2b7d0c3d9660fea613a2ad90c240bd02c1eefa4a55e9038ce74dcfdd34e278ea0436e261131a36fa4e922f0a077ca1c9842f654928aac3ca7f9341075f9db275d8286b5ef13e7f91b4837e77b2a6dbea83f86b90f848331053d8a6b1fbc26787992e7fb819a2005bae9b3026b9c7d1158e88e4a2018f13757083c7873241d2dfe6ea46a17cd6f3d090f3e0da44ccfbd6bc425124de1bea744a32f3ab175672a991ef274cd83550eca57ea591b85fa9799098a38ec552dc3ec679c431491444820624f5c4ba0c8cf87d60af89899afce2a90325c6966dcf">

<input name="file" type="file">
<input type="submit" value="Upload">
</form>

C++

C++

For more information, see the Cloud Storage C++ API reference documentation.

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  auto document = client.GenerateSignedPostPolicyV4(
      gcs::PolicyDocumentV4{
          bucket_name,
          object_name,
          /*expiration=*/std::chrono::minutes(10),
      },
      gcs::AddExtensionFieldOption("x-goog-meta-test", "data"));
  if (!document) throw std::runtime_error(document.status().message());

  // Create the HTML form for the computed policy.
  std::ostringstream os;
  os << "<form action='" << document->url << "' method='POST'"
     << " enctype='multipart/form-data'>\n";
  for (auto const& field : document->required_form_fields) {
    os << "  <input name='" << field.first << "' value='" << field.second
       << "' type='hidden' />\n";
  }
  os << "  <input type='submit' value='Upload File' name='submit' /><br />\n"
     << "  <input type='file' name='file' /><br />\n"
     << "</form>";

  std::cout << "A sample HTML form:\n" << os.str() << "\n";
}

C#

C#

For more information, see the Cloud Storage C# API reference documentation.

// Create a signed post policy which can be used to upload a specific object and
// expires in 1 hour after creation.
UrlSigner urlSigner = UrlSigner
    .FromServiceAccountCredential(credential);
UrlSigner.Options options = UrlSigner.Options
    .FromDuration(TimeSpan.FromHours(1))
    .WithSigningVersion(SigningVersion.V4)
    .WithScheme("https");
UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName);
postPolicy.SetCustomField(UrlSigner.PostPolicyCustomElement.GoogleMetadata, "x-goog-meta-test", "data");

UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options);

// Create an HTML form including all the fields in the signed post policy.
StringBuilder form = new StringBuilder();
form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">");
foreach (var field in signedPostPolicy.Fields)
{
    form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">");
}
// Include the file element. It should always be the last element in the form.
form.AppendLine("<input name=\"file\" type=\"file\">");
form.AppendLine("<input type=\"submit\" value=\"Upload\">");
form.AppendLine("</form>");

// You can now save the form to file and serve it as static content
// or send it as the response to a request made to your application.
File.WriteAllText("PostPolicySimple.html", form.ToString());

Java

Java

For more information, see the Cloud Storage Java API reference documentation.

import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.PostPolicyV4;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class GenerateSignedPostPolicyV4 {
  /**
   * Generating a signed POST policy requires Credentials which implement ServiceAccountSigner.
   * These can be set explicitly using the Storage.PostPolicyV4Option.signWith(ServiceAccountSigner)
   * option. If you don't, you could also pass a service account signer to StorageOptions, i.e.
   * StorageOptions().newBuilder().setCredentials(ServiceAccountSignerCredentials). In this example,
   * neither of these options are used, which means the following code only works when the
   * credentials are defined via the environment variable GOOGLE_APPLICATION_CREDENTIALS, and those
   * credentials are authorized to sign a policy. See the documentation for
   * Storage.generateSignedPostPolicyV4 for more details.
   */
  public static void generateSignedPostPolicyV4(
      String projectId, String bucketName, String blobName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of the GCS bucket to upload to
    // String bucketName = "your-bucket-name"

    // The name to give the object uploaded to GCS
    // String blobName = "your-object-name"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    PostPolicyV4.PostFieldsV4 fields =
        PostPolicyV4.PostFieldsV4.newBuilder().AddCustomMetadataField("test", "data").build();

    PostPolicyV4 policy =
        storage.generateSignedPostPolicyV4(
            BlobInfo.newBuilder(bucketName, blobName).build(), 10, TimeUnit.MINUTES, fields);

    StringBuilder htmlForm =
        new StringBuilder(
            "<form action='"
                + policy.getUrl()
                + "' method='POST' enctype='multipart/form-data'>\n");
    for (Map.Entry<String, String> entry : policy.getFields().entrySet()) {
      htmlForm.append(
          "  <input name='"
              + entry.getKey()
              + "' value='"
              + entry.getValue()
              + "' type='hidden' />\n");
    }
    htmlForm.append("  <input type='file' name='file'/><br />\n");
    htmlForm.append("  <input type='submit' value='Upload File' name='submit'/><br />\n");
    htmlForm.append("</form>\n");

    System.out.println(
        "You can use the following HTML form to upload an object to bucket "
            + bucketName
            + " for the next ten minutes:");
    System.out.println(htmlForm.toString());
  }
}

Go

Go

For more information, see the Cloud Storage Go API reference documentation.

import (
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"time"

	"cloud.google.com/go/storage"
	"golang.org/x/oauth2/google"
)

// form is a template for an HTML form that will use the data from the signed
// post policy.
var form = `<form action="{{ .URL }}" method="POST" enctype="multipart/form-data">
	{{- range $name, $value := .Fields }}	<input name="{{ $name }}" value="{{ $value }}" type="hidden"/>
	{{- end }}	<input type="file" name="file"/><br />
	<input type="submit" value="Upload File" name="submit"/><br />
</form>`

var tmpl = template.Must(template.New("policyV4").Parse(form))

// generateSignedPostPolicyV4 generates a signed post policy.
func generateSignedPostPolicyV4(w io.Writer, bucket, object, serviceAccountJSONPath string) (*storage.PostPolicyV4, error) {
	// bucket := "bucket-name"
	// object := "object-name"
	// serviceAccountJSONPath := "service_account.json"
	jsonKey, err := ioutil.ReadFile(serviceAccountJSONPath)
	if err != nil {
		return nil, fmt.Errorf("ioutil.ReadFile: %v", err)
	}
	conf, err := google.JWTConfigFromJSON(jsonKey)
	if err != nil {
		return nil, fmt.Errorf("google.JWTConfigFromJSON: %v", err)
	}
	metadata := map[string]string{
		"x-goog-meta-test": "data",
	}
	opts := &storage.PostPolicyV4Options{
		GoogleAccessID: conf.Email,
		PrivateKey:     conf.PrivateKey,
		Expires:        time.Now().Add(10 * time.Minute),
		Fields: &storage.PolicyV4Fields{
			Metadata: metadata,
		},
	}

	policy, err := storage.GenerateSignedPostPolicyV4(bucket, object, opts)
	if err != nil {
		return nil, fmt.Errorf("storage.GenerateSignedPostPolicyV4: %v", err)
	}

	// Generate the form, using the data from the policy.
	if err = tmpl.Execute(w, policy); err != nil {
		return policy, fmt.Errorf("executing template: %v", err)
	}

	return policy, nil
}

Node.js

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function generateV4SignedPolicy() {
  const bucket = storage.bucket(bucketName);
  const file = bucket.file(filename);

  // These options will allow temporary uploading of a file
  // through an HTML form.
  const expires = Date.now() + 10 * 60 * 1000; //  10 minutes
  const options = {
    expires,
    fields: {'x-goog-meta-test': 'data'},
  };

  // Get a v4 signed policy for uploading file
  const [response] = await file.generateSignedPostPolicyV4(options);

  // Create an HTML form with the provided policy
  let output = `<form action='${response.url}' method='POST' enctype="multipart/form-data">\n`;
  // Include all fields returned in the HTML form as they're required
  for (const name of Object.keys(response.fields)) {
    const value = response.fields[name];
    output += `  <input name='${name}' value='${value}' type='hidden'/>\n`;
  }
  output += "  <input type='file' name='file'/><br />\n";
  output +=
    "  <input type='submit' value='Upload File' name='submit'/><br />\n";
  output += '</form>';

  console.log(output);
}

generateV4SignedPolicy().catch(console.error);

PHP

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Generates a V4 POST Policy to be used in an HTML form and echo's form.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 *
 * @return void
 */
function generate_v4_post_policy($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $response = $bucket->generateSignedPostPolicyV4(
        $objectName,
        new \DateTime('10 min'),
        [
            'fields' => [
                'x-goog-meta-test' => 'data'
            ]
        ]
    );

    $url = $response['url'];
    $output = "<form action='$url' method='POST' enctype='multipart/form-data'>" . PHP_EOL;
    foreach ($response['fields'] as $name => $value) {
        $output .= "  <input name='$name' value='$value' type='hidden'/>" . PHP_EOL;
    }
    $output .= "  <input type='file' name='file'/><br />" . PHP_EOL;
    $output .= "  <input type='submit' value='Upload File' name='submit'/><br />" . PHP_EOL;
    $output .= "</form>" . PHP_EOL;

    echo $output;
}

Python

Python

For more information, see the Cloud Storage Python API reference documentation.

import datetime

from google.cloud import storage


def generate_signed_post_policy_v4(bucket_name, blob_name):
    """Generates a v4 POST Policy and prints an HTML form."""
    # bucket_name = 'your-bucket-name'
    # blob_name = 'your-object-name'

    storage_client = storage.Client()

    policy = storage_client.generate_signed_post_policy_v4(
        bucket_name,
        blob_name,
        expiration=datetime.timedelta(minutes=10),
        fields={
          'x-goog-meta-test': 'data'
        }
    )

    # Create an HTML form with the provided policy
    header = "<form action='{}' method='POST' enctype='multipart/form-data'>\n"
    form = header.format(policy["url"])

    # Include all fields returned in the HTML form as they're required
    for key, value in policy["fields"].items():
        form += "  <input name='{}' value='{}' type='hidden'/>\n".format(key, value)

    form += "  <input type='file' name='file'/><br />\n"
    form += "  <input type='submit' value='Upload File' /><br />\n"
    form += "</form>"

    print(form)

    return form

Ruby

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file to create in the Cloud Storage bucket"
require "google/cloud/storage"

storage = Google::Cloud::Storage.new

bucket = storage.bucket bucket_name
post_object = bucket.generate_signed_post_policy_v4 file_name,
                                                    expires: 600,
                                                    fields:  { "x-goog-meta-test": "data" }

html_form = "<form action='#{post_object.url}' method='POST' enctype='multipart/form-data'>\n"
post_object.fields.each do |name, value|
  html_form += "  <input name='#{name}' value='#{value}' type='hidden'/>\n"
end
html_form += "  <input type='file' name='file'/><br />\n"
html_form += "  <input type='submit' value='Upload File' name='submit'/><br />\n"
html_form += "</form>\n"

puts html_form

As a best practice you should use the Expect: 100-continue header with POST requests. This allows you to verify that the server will handle the request before you send the object. If you receive a status code 100 Continue you should proceed with the request. If you receive a status code 417 Expectation Failed then you should not send the object.