如何使用Java从Google云端存储下载文件?

Tom*_*ere 3 java google-cloud-storage

我正在开发一个应用程序,为用户提供一个界面,可以从我们的Google云端存储中下载文件.我编写了单元测试,我可以连接到存储并下载文件.

现在我(几乎)完成了我的界面,我想测试整个应用程序.但现在我注意到我并没有真正下载该文件,我下载了一个文件,其中包含有关我要下载的文件的META数据.就像是:

{
 "kind": "storage#object",
 "id": "xxxxxxxxxxx/Homer.png/xxxxxxxxxxxx",
 "selfLink": "https://www.googleapis.com/storage/xxxxxxxxxxxxxxxx/Homer.png",
 "name": "Homer.png",
 "bucket": "xxxxxxxxxxxxxxx",
 "generation": "xxxxxxxxxxxxxxx",
 "metageneration": "1",
 "contentType": "image/png",
 "updated": "2014-07-17T08:37:28.026Z",
 "storageClass": "STANDARD",
 "size": "xxxxx",
 "md5Hash": "xxxxxxxxxxxxxxxxxxxxx",
 "mediaLink": "https://www.googleapis.com/download/storage/xxxxxxxxxxxxxxx/o/Homer.png?generation=xxxxxxxxxxxxxxxxx&alt=media",
 "owner": {
  "entity": "user-xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "entityId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 },
 "crc32c": "xxxxxxxxxx",
 "etag": "xxxxxxxxxxxxx"
}
Run Code Online (Sandbox Code Playgroud)

我想知道我做错了什么,这是我用来下载文件的代码:

public byte[] getFileAsByteArray(String bucketName, String fileName)
        throws GoogleAppManagerException {
        Storage storage = null;
        try {
            storage = getStorage();
        } catch (GeneralSecurityException e) {
            throw new GoogleAppManagerException(SECURITY_EXCEPTION + e.getStackTrace(), e);
        } catch (IOException e) {
            throw new GoogleAppManagerException(IO_EXCEPTION + e.getStackTrace(), e);
        }
        Get get = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            get = storage.objects().get(bucketName, fileName);
            get.executeAndDownloadTo(outputStream);
        } catch (IOException e1) {
            throw new GoogleAppManagerException(IO_EXCEPTION + e1.getStackTrace(), e1);
        }
        return outputStream.toByteArray();
    }
Run Code Online (Sandbox Code Playgroud)

小智 7

使用最新的:

Storage storage = StorageOptions.newBuilder()
            .setProjectId(projectId)
            .setCredentials(GoogleCredentials.fromStream(new FileInputStream(serviceAccountJSON)))
            .build()
            .getService();
Blob blob = storage.get(BUCKET_URL, RELATIVE_OBJECT_LOCATION);
ReadChannel readChannel = blob.reader();
FileOutputStream fileOuputStream = new FileOutputStream(outputFileName);
fileOuputStream.getChannel().transferFrom(readChannel, 0, Long.MAX_VALUE);
fileOuputStream.close();
Run Code Online (Sandbox Code Playgroud)


jte*_*ace 3

正如您所说,当前您正在下载元数据。您需要使用媒体下载来下载对象的数据。

在这里查看示例 Java 代码: https://developers.google.com/storage/docs/json_api/v1/objects/get

这是最简单的方法,使用getMediaHttpDownloader().

有关媒体和另一种方法(可恢复下载)的更多信息,请参见: https: //code.google.com/p/google-api-java-client/wiki/MediaDownload