Search code examples
javagoogle-app-engineservletsblobstore

Finding a blob in Google AppEngine's BlobStore with BlobKey


I'm trying to save and then serve a blob on GoogleAppEngine.

// Save the data as a blob
final FileService fileService = FileServiceFactory.getFileService();
final AppEngineFile file = fileService.createNewBlobFile("application/zip", "nameOfSavedFile");
final FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
writeChannel.write(ByteBuffer.wrap(data));
writeChannel.closeFinally();

// Load the blob data
Query query = new Query("__BlobInfo__"); 
query.addFilter("filename", FilterOperator.EQUAL, "nameOfSavedFile"); 
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 
PreparedQuery pq = datastore.prepare(query); 
List<Entity> entList = pq.asList(FetchOptions.Builder.withLimit(1)); 
String blobKeyString = entList.get(0).getKey().getName();

BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
BlobKey blobKeyLoaded = new BlobKey(blobKeyString);
blobStoreService.serve(blobKeyLoaded,response);

If I run the above code once it seems to work. But when I run the same code again with the intention of overwriting the existing file with a new file of the same name it just serves the old file.

Can anyone explain how to make it overwrite the old file with a new one?

Thanks!


Solution

  • AFAIK, BlobInfo is only produced/updated if you upload the blob via the upload handler.

    If you change blob "manually", i.e. via FileService, then BlobInfo does not get created/updated. In this case you should update BlobInfo manually, or not use it at all and just store key/name in your custom entities.