我想上传简单的图像文件到谷歌 Cloud 存储,当上传是根桶上传发生顺利,但当我尝试将图像上传到一个桶内的文件夹,它失败
以下是我的代码
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 回答
GCS具有平面命名空间,“文件夹”只是客户端支持的抽象(基本上,将对象名称中的“/”字符视为文件夹分隔符) .
因此,要上传到文件夹,您应该只将桶名放在请求的存储区字段中,并将文件夹放在对象字段的开头 . 例如,要上传到存储桶'my-bucket',文件夹'my-folder'和文件夹'文件',您可以将存储桶名称设置为'my-bucket',将对象名称设置为'my-folder /文件' .