【问题标题】:How do I access CSV data from Google App Engine?如何从 Google App Engine 访问 CSV 数据?
【发布时间】:2014-12-16 07:18:51
【问题描述】:

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

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

或者,有没有办法上传 blob,然后将数据映射到 Cloud Storage?

【问题讨论】:

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


【解决方案1】:

如果您按照此处的代码https://cloud.google.com/appengine/docs/java/blobstore/ 操作,它将指导您设置上传 URL 并提供回调 URL 等...当文件上传并调用您的回调 URL 时,您需要记住 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");
    }
 }

【讨论】:

  • 啊哈!谢谢 omerio,我会玩这个,看看我的进展如何
猜你喜欢
  • 1970-01-01
  • 2015-11-05
  • 2016-01-26
  • 1970-01-01
  • 2013-09-01
  • 2012-03-15
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多