我正在开发一个应用程序,为用户提供可以从我们的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"
}
我想知道我做错了什么,这是我用来下载文件的代码:
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();
}
答案 0 :(得分:7)
使用最新的libraries:
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();
答案 1 :(得分: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
答案 2 :(得分:0)
@AnandMohan是正确的。您只需要在“ tmp”文件夹上进行复制,因为所有位置都是只读的,只有“ tmp”是可写的。检查以下内容:
"scripts": {
"postshrinkwrap": "lockfix",
},