如何从Google App Engine访问CSV数据?

时间:2014-10-21 06:36:44

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

我有一个简单的网络应用,可让用户将CSV上传到GAE blob存储空间。我试图将该数据传递给谷歌分析API方法,但我无法弄清楚如何。在教程文档之后,我似乎只能在响应头中返回该文件。

有没有办法将blob作为文件直接传递给方法?

或者有没有办法上传blob,然后将数据映射到云端存储?

1 个答案:

答案 0 :(得分:2)

如果您按照此处的代码https://cloud.google.com/appengine/docs/java/blobstore/,它将指导您设置上传网址并提供回调网址等...当文件上传并且您的回调网址被调用时,您需要记住blob密钥,您可以保存在数据存储区中,将其保存在会话中或根据需要随意从数据存储区读取blob。

下面的代码应该有所帮助,特别是您感兴趣的方法是 getBlobAsString ,或者您只需使用blobStream( BlobstoreInputStream blobStream = new BlobstoreInputStream(blobKey); )将文件内容作为InputStream传递

处理上传回调的servlet

import org.apache.commons.io.IOUtils;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreInputStream;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

public class Upload extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        BlobKey blobKey = blobs.get("myFile");

        if (blobKey != null) {
            String keyString = blobKey.getKeyString();
            // you can store keyString in the datastore or whatever
            // if you want the call the analytics API then you need the blob as string

             String csv = getBlobAsString(keyString);

             // you can do with csv whatever you like, convert it as an array, etc... then pass it
             // over to the analytic API
        } 
    }


   public static String getBlobAsString(String keyString) throws IOException {
        BlobKey blobKey = new BlobKey(keyString);
        BlobstoreInputStream blobStream = new BlobstoreInputStream(blobKey);

        return IOUtils.toString(blobStream, "UTF-8");
    }
 }