有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从其BlobKey获取Google云存储文件

我编写了一个GoogleAppEngine应用程序,它利用Blobstore保存编程生成的数据。为此,我使用了Files API,不幸的是,它已经被弃用,转而支持谷歌云存储。因此,我正在重写我的助手类以与GCS一起工作

我希望保持界面尽可能与以前相似,还因为我在数据存储中保留BlobKeys以保留对文件的引用(更改生产应用程序的模型总是很痛苦)。当我把东西保存到地面军事系统时,我用

BlobKey blobKey = blobstoreService.createGsBlobKey("/gs/" + fileName.getBucketName() + "/" + fileName.getObjectName());

按照规定here,我将其保存在数据存储中

所以这里有一个问题:文档告诉我如何在servlet响应中使用blobstoreService.serve(blobKey, resp);为GCS文件提供服务,但是我如何检索文件内容(作为InputStream、字节数组或其他内容)以便在代码中使用它进行进一步处理?在我当前的实现中,我使用FileReadChannel读取AppEngineFile(两者都不推荐使用)


共 (4) 个答案

  1. # 1 楼答案

    以下是Blobstore方法(抱歉,这是针对Python的,但我相信您会发现它与Java非常相似):

    blob_reader = blobstore.BlobReader(blob_key)
    if blob_reader:
      file_content = blob_reader.read()
    
  2. # 2 楼答案

    只能在上载处理程序(fileInfo.gs_object_name)中获取cloudstorage文件名,并将其存储在数据库中。在这之后,它就丢失了,并且似乎没有保存在BlobInfo或其他元数据结构中

    Google says: Unlike BlobInfo metadata FileInfo metadata is not persisted to datastore. (There is no blob key either, but you can create one later if needed by calling create_gs_key.) You must save the gs_object_name yourself in your upload handler or this data will be lost.

    抱歉,这是一个python链接,但在java中应该很容易找到类似的东西。 https://developers.google.com/appengine/docs/python/blobstore/fileinfoclass

  3. # 3 楼答案

    给定一个blobKey,使用^{}类从Blobstore读取值,如documentation中所述:

    BlobstoreInputStream in = new BlobstoreInputStream(blobKey); 
    
  4. # 4 楼答案

    下面是打开Google存储对象作为输入流的代码。不幸的是,您必须使用bucket name和object name,而不是blob键

    GcsFilename gcs_filename = new GcsFilename(bucket_name, object_name);
    GcsService service = GcsServiceFactory.createGcsService();
    ReadableByteChannel rbc = service.openReadChannel(gcs_filename, 0);
    InputStream stream = Channels.newInputStream(rbc);