Michael King
Michael King

Reputation: 415

How do I access CSV data from Google App Engine?

I have a simple web app that lets users upload a CSV to GAE blob storage. I am trying to pass that data to a google analytics API method but I cannot work out how. Following the tutorial doc, I only seem to be able to return the file in the response header.

Is there a way to pass the blob directly to the method as a file?

Alternatively is there a way to upload a blob and then map the data to Cloud Storage?

Upvotes: 1

Views: 877

Answers (1)

omerio
omerio

Reputation: 1196

If you follow the code here https://cloud.google.com/appengine/docs/java/blobstore/ it will guide you through setting up the upload URL and providing a callback URL, etc... When the file is uploaded and your callback URL is called you need to remember the blob key, you can save in the datastore, keep it in the session or whatever as you need it to read the blob back from the Datastore.

The code below should help, in particular the method your interested in is getBlobAsString or you can simply use the blobStream (BlobstoreInputStream blobStream = new BlobstoreInputStream(blobKey);) to pass the file content around as an InputStream

In your servlet handling the upload callback

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");
    }
 }

Upvotes: 2

Related Questions