Uploading And Serving Files With The Blobstore In Java

Here’s a code example to let users upload a file to the Blobstore and then download it back again. This code uses a servlet and a JSP page: the JSP page shows a form and the servlet accepts the upload, then immediately sends the uploaded file back to the user.

Here’s the doPost and doGet code for the servlet (in this example, we aliased the servlet to /blobstoreexample):

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    String blob_key_string = req.getParameter("blob_key");
    System.out.println("BLOBKEY: " + blob_key_string);
    if (blob_key_string == null) {
        resp.sendRedirect("/example.jsp");
        System.out.println("No blobkey given, redirecting to upload page.");
    }
    else {
        BlobKey blob_key = new BlobKey(blob_key_string);
        BlobstoreServiceFactory.getBlobstoreService().serve(blob_key, resp);
        System.out.println("Blobkey given, sending file.");
    }
}//end doGet


public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    try {
        Map<String, List<BlobKey>> files_sent = BlobstoreServiceFactory.getBlobstoreService().getUploads(req);
        BlobKey file_uploaded_key = files_sent.get("file").get(0);
        resp.sendRedirect("/blobstoreexample?blob_key=" + file_uploaded_key.getKeyString());
        System.out.println("Document successfully POSTED, redirect to doGET");
    }
    catch (Exception e) {
        resp.sendRedirect("/example.jsp");
        System.out.println("Document failed to POST, redirecting back to upload.");
    }
}//end doPost

Here is the code for example.jsp (remember to import the Blobstore library):

<form enctype="multipart/form-data" method="post" action="<%= BlobstoreServiceFactory.getBlobstoreService().createUploadUrl("/blobstoreexample") %>">
<input type="file" name="file" size="30" />
<input type="submit" /></form>

You can add additional form elements to the form if needed; the servlet will be able to access them.