Question

I've spent days researching, and I can't seem to find this. Is there a way to upload a blob that has already been uploaded to the blobstore in Google and upload that to my drive. I'm able to create new documents, but not upload already existing files from the blobstore to the user's drive. I can't use FileOutputStream in the Google App Engine environment, and I can't use the blobstore's upload url either it seems.

Was it helpful?

Solution

I assume that you have the OAuth2 access token. If that is the case, something like the following should do the job. It requires reading the blob file into a byte array. I have not found a way to do streaming, so if the file is big you will have to resort to writing the blob out into the disk drive first.

import com.google.api.client.http.ByteArrayContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

// creates the credential object from the OAuth2 Access Token
GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(TRANSPORT).setJsonFactory(JSON_FACTORY)
    .setClientSecrets(clientSecrets.getWeb().getClientId(), clientSecrets.getWeb().getClientSecret())
    .build();
credential.setAccessToken(accessToken);

Drive drive = Drive.Builder(TRANSPORT, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();


// reads the blobstore file into a byte array
BlobKey blobKey = new BlobKey(blobKeyStr);
byte[] blobBytes = blobstoreService.fetchData(blobKey, 0, BlobstoreService.MAX_BLOB_FETCH_SIZE-1);

// creates the google drive file
String parentId = ...; // find the parent reference for the google drive file
File file = new File();
file.setMimeType(mimeType);
file.setTitle(...);
file.setParents(Arrays.asList(new ParentReference().setId(parentId)));
drive.files().insert(file, new ByteArrayContent(mimeType, blobBytes)).execute();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top