如何将文件上传到GCS存储桶Android中存在的文件夹中

时间:2020-09-27 08:29:20

标签: java android google-cloud-storage

我正在按照这个github教程将文件上传到GCS存储桶

https://github.com/thorrism/GoogleCloudExample

图像已成功上传到存储桶中。

但是我想将文件上传到存储桶中当前存在的文件夹中

例如

KS_bucket是存储桶名称,images是KS_bucket内部的文件夹名称。

我试图这样指定存储桶名称

KS_bucket /图像或KS_bucket /图像/

但是我收到无效的存储桶名称错误

. W/System.err: {
2020-09-27 13:04:01.416 32172-32247/com. W/System.err:   "code" : 400,
2020-09-27 13:04:01.416 32172-32247/com. W/System.err:   "errors" : [ {
2020-09-27 13:04:01.416 32172-32247/ W/System.err:     "domain" : "global",
2020-09-27 13:04:01.416 32172-32247/com. W/System.err:     "message" : "Invalid bucket name: 'kS_bucket/images'",
2020-09-27 13:04:01.416 32172-32247/com. W/System.err:     "reason" : "invalid"
2020-09-27 13:04:01.416 32172-32247/com. W/System.err:   } ],
2020-09-27 13:04:01.416 32172-32247/com. W/System.err:   "message" : "Invalid bucket name: 'ks_bucket/images'"
2020-09-27 13:04:01.416 32172-32247/com..W/System.err: }

我用于上传的方法

 public static void uploadFile(String bucketName, String filePath)
            throws Exception {
       
        Storage storage = getStorage();

        StorageObject object = new StorageObject();
        object.setBucket(bucketName);

        File file = new File(filePath);

        InputStream stream = new FileInputStream(file);
        try {
            String contentType = URLConnection
                    .guessContentTypeFromStream(stream);
            InputStreamContent content = new InputStreamContent(contentType,
                    stream);

            Storage.Objects.Insert insert = storage.objects().insert(
                    bucketName, null, content);
            insert.setName(file.getName());
            insert.execute();
        } finally {
            stream.close();
        }
    }

希望对此有所帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

您正在此处尝试设置存储桶名称,其中带有“ /”的名称在Cloud Storage中无效。您需要做的就是在将文件插入存储桶之前更改文件的名称,包括其文件夹名称。 setName是您在这里需要使用的:

insert.setName('folder/filename');

类似的东西