将对象上传到谷歌云存储桶java

时间:2018-01-17 14:32:59

标签: java google-cloud-storage

我想将简单的图片文件上传到Google云端存储 当上传到根桶时,上传顺利进行,但是当我尝试将图片上传到存储桶中的文件夹时,它会失败

以下是我的代码

 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();
    }
}

我尝试将广告名称设为[PARENT_BUCKET]/[CHILD_FOLDER] 但它不起作用

1 个答案:

答案 0 :(得分:3)

GCS具有平面命名空间,“文件夹”只是客户端支持的抽象(基本上,将对象名称中的“/”字符视为文件夹分隔符)。

因此,要上传到文件夹,您应该只将桶名放在请求的bucket字段中,并将文件夹放在object字段的开头。例如,要上传到存储桶'my-bucket',文件夹'my-folder'和文件夹'文件',您可以将存储桶名称设置为'my-bucket',将对象名称设置为'my-folder /文件”。

相关问题