Insert object (as a folder) in Google Cloud Storage using JSON API with Java
-
21-12-2019 - |
Question
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.
OTHER TIPS
I dont think you can create a folder that way. But you can create it while uploading the file by setting the name.
e.g. if you want create a file under foldA/foldB/test.txt, you can do it following way.
InputStream is = Files.newInputStream(path); //path if java.nio.file.Path
String mimeType = Files.probeContentType(path);
InputStreamContent isContent = new InputStreamContent(mimeType, is);
StorageObject objectMetadata = new StorageObject();
Storage.Objects.Insert insertObject = storage.objects().insert(bucketRootName, objectMetadata,isContent);
insertObject.setName("foldA/foldB/"+path.getFileName().toString()); // path.getFileName().toString() will give u test.txt
insertObject.execute();