0
votes

I want to upload simple image file to google cloud storage when the upload is to root bucket upload happens smoothly but when i try to upload image to folder within a bucket it fails

following is my code to do so

 static Storage sStorage;
 public static void uploadFileToServer(Context context, String filePath) {
    Storage storage = getStorage(context);
    StorageObject object = new StorageObject();
    object.setBucket(BUCKET_NAME);
    File sdCard = Environment.getExternalStorageDirectory();
    File file = new File(sdCard + filePath);
    try {
        InputStream stream = new FileInputStream(file);
        String contentType = URLConnection.guessContentTypeFromStream(stream);
        InputStreamContent content = new InputStreamContent(contentType, stream);

        Storage.Objects.Insert insert = storage.objects().insert(BUCKET_NAME, null, content);
        insert.setName(file.getName());
        insert.execute();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

i tried putting bucket name like [PARENT_BUCKET]/[CHILD_FOLDER] but it doesn't work

1

1 Answers

3
votes

GCS has a flat namespace, with "folders" being just a client-supported abstraction (basically, treating "/" characters in object names as the folder delimiter).

So, to upload to a folder you should put just the bucket name in the bucket field of the request, and put the folder at the beginning of of the object field. For example, to upload to bucket 'my-bucket', folder 'my-folder' and file-within-folder 'file', you'd set bucket name to 'my-bucket' and object name to 'my-folder/file'.