如何使用GAE在谷歌云存储中上传文件

时间:2012-12-21 05:57:02

标签: java google-app-engine google-cloud-storage

在GAE中上传文件时,我可以使用以下代码,

 //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);

现在,如果我需要在Google云存储中同样上传文件,我可以设置存储分区并打开以下频道,

//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);

此后我不知道如何将文件存储在Google云端存储中。我引用了这个开发人员页面Google Cloud Storage Java API Overview,但它只显示对象的读取和写入而不上传文件。

请建议我在Google云存储中上传文件。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

这样的事情:

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

然后对该网址进行POST。但是,然后在'/ on_upload_success'处理程序中,您从GS获取文件的BlobKey,但不是文件名(由于此错误http://code.google.com/p/googleappengine/issues/detail?id=8337)。那么你只能使用blobkey从GAE读取数据。