Search code examples
javajsongoogle-app-enginegoogle-cloud-storagecloud-storage

Insert object (as a folder) in Google Cloud Storage using JSON API with Java


I already know that there is no folders inside a Google Cloud Storage (they are treated as objects), so please have a look of my question and you can understand what i mean. Thanks :-)

This is my method to upload an object, and in my specific case, i would like to upload a "folder", so a file that end with a '/' (for example: 'newfolder/'), but i receive a GoogleJson error in the execute() at the end of my code.

[Error]:

Uncaught exception from servlet
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 OK
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Required",
    "reason" : "required"
  }, {
    "domain" : "global",
    "message" : "Required",
    "reason" : "required"
  }, {
    "domain" : "global",
    "message" : "Required",
    "reason" : "required"
  } ],
  "message" : "Required"
}

[my code inside the method]:

StorageObject objectMetadata = null;

        //default bucket
        String bucketRootName = “defaultbucketname”;

        //First Folder
        String folderAppName = “myfolder”;

        //folder that i want to create (upload)
        folderName+="/";
        String folderPath = folderAppName + "/" + folderName;

        if (useCustomMetadata) {

            List<ObjectAccessControl> acl = Lists.newArrayList();
            acl.add( new ObjectAccessControl().setEntity("allAuthenticatedUsers").setRole("OWNER"));

            objectMetadata = new StorageObject()

            .setName(folderPath)
            .setAcl(acl)
            .setContentDisposition("attachment");
        }

        Storage.Objects.Insert insertObject = storage.objects().insert(bucketRootName, objectMetadata);

        StorageObject metadata = insertObject.execute();
        return metadata;

In order to have a bucket with a path like this: defaultbucketname/myfolder/folderName/

Does anyone know how to solve it?

Thank you so much


Solution

  • Uploaded objects must have a Content-Type, even if they're zero bytes large.

    Also, I'm pretty sure that you must upload an actual file, even if it is zero bytes in size.