how can i upload a file in google cloud storage us

2019-08-05 18:52发布

问题:

When uploading a file in GAE i can use the code as follows,

 //here creating a blob store service
    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
//here declaring the datastore service
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//creating entity
   Entity emp = new Entity("Employee");
//set the property
   emp.setProperty("First Name", fname);
   emp.setProperty("Last Name", lname);
//storing the data in GAE
   datastore.put(Employee);

Now if i need to do the same uploading of a file in Google cloud storage, I can set the bucket and open the channels as below,

//Creating file service
FileService fileService = FileServiceFactory.getFileService();

//setting bucket name,object name & type
GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
       .setBucket(BUCKETNAME)
       .setKey(FILENAME)
       .setMimeType("text/html")
       .setAcl("public_read")
       .addUserMetadata("myfield1", "my field value");

//creating the new writable file 
 AppEngineFile writableFile =fileService.createNewGSFile(optionsBuilder.build());
//opening the lock and writing channel
boolean lock = false;
FileWriteChannel writeChannel = fileService.openWriteChannel(writableFile, lock);

After this i don't know how to store the file in the Google cloud storage. I referenced this developers page Google Cloud Storage Java API Overview but it shows only reading and writing to object not uploading the file.

Kindly suggest me an idea for uploading the file in Google cloud storage.

Your help is appreciated.

回答1:

Something like this:

UploadOptions uploadOptions = UploadOptions.Builder.withGoogleStorageBucketName("bucket");
String uploadUrl = blobstoreService.createUploadUrl("/on_upload_success", uploadOptions));

Then do POST to that url. However, then in '/on_upload_success' handler you're getting BlobKey of a file from GS, but not file name (due to this bug http://code.google.com/p/googleappengine/issues/detail?id=8337). So then you only can read that data from GAE using blobkey.