在GAE blobstore java中创建文件

时间:2016-03-08 15:37:33

标签: java google-app-engine

在我的应用程序中,我有一个字符串,它是一个文件内容。我需要在blobstore中使用此内容创建新文件。我试着像这样使用File API:

    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile file = fileService.createNewBlobFile("text/plain");
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);

    writeChannel.write(ByteBuffer.wrap(content.getBytes()));
    writeChannel.closeFinally();
    BlobKey blobKey = fileService.getBlobKey(file);
    res.sendRedirect("/serve?blob-key=" + blobKey);

但是由于不推荐使用File API,我只会收到此错误:

HTTP ERROR 500

Problem accessing /create_timetable. Reason:

The Files API is disabled. Further information: https://cloud.google.com/appengine/docs/deprecations/files_api
Caused by:

com.google.apphosting.api.ApiProxy$FeatureNotEnabledException: The Files API is disabled. Further information: https://cloud.google.com/appengine/docs/deprecations/files_api
at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.callInternal(ApiProxyLocalImpl.java:515)
at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:484)
at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:461)
at java.util.concurrent.Executors$PrivilegedCallable$1.run(Executors.java:533)
at java.security.AccessController.doPrivileged(Native Method)
at java.util.concurrent.Executors$PrivilegedCallable.call(Executors.java:530)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

如何在blobstore中手动创建文件,因为用户只将数据内容作为字符串,而不是文件本身,因此我无法使用<form action="blobstoreService.createUploadUrl("/upload") %>"<input type="file">

更新

正如@ozarov建议我使用Google Cloude Storage API完成它并编写了下面的函数。它还返回此文件的BlobKey,以便您可以使用Blobstore API访问它。

private BlobKey saveFile(String gcsBucket, String fileName,
        String content) throws IOException {
    GcsFilename gcsFileName = new GcsFilename(gcsBucket, fileName);
    GcsOutputChannel outputChannel =
            gcsService.createOrReplace(gcsFileName, GcsFileOptions.getDefaultInstance());
    outputChannel.write(ByteBuffer.wrap(content.getBytes()));
    outputChannel.close();

    return blobstoreService.createGsBlobKey(
            "/gs/" + gcsFileName.getBucketName() + "/" + gcsFileName.getObjectName());
}

1 个答案:

答案 0 :(得分:2)

您应该写信至Google Cloud Storage。 文件API是deprecated,你是正确的Blobstore API 没有提供直接写入它的程序化方法。

稍后您可以使用自己的API或直接从Google云端存储中读取 您也可以使用Blobstore API通过creating BlobKey为它执行此操作。