chuntato
chuntato

Reputation: 128

Writing byte array to GAE Blobstore

I'm able to read the bytes and print it out on System console. However since GAE does not support file creation, I search through StackOverflow and found out that I can write into GAE blobstore. But I'm not sure how to go about doing it as I'm new to GAE..

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html;charset=UTF-8");
    // resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(req);
        // out.println("<html><body>");

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();

            if (item.isFormField()) {
                out.println("<br />Got a form field: " + item.getFieldName());
            } else {
                out.println("<br />Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

                ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream( in ));

                ZipEntry entry;

                // Read each entry from the ZipInputStream until no
                // more entry found indicated by a null return value
                // of the getNextEntry() method.

                byte[] buf = new byte[10244];
                int len;
                while ((entry = zis.getNextEntry()) != null) {

                    out.println("Unzipping: " + entry.getName());

                    FileService fileService = FileServiceFactory.getFileService();

                    AppEngineFile file = fileService.createNewBlobFile("text/plain");

                    boolean lock = false;
                    FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

                    PrintWriter outter = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));

                    StringBuilder sb = new StringBuilder(buf.length);
                    if (entry.getName().equalsIgnoreCase("booking.csv")) {
                        int count = 0;
                        while ((len = zis.read(buf, 0, buf.length)) != -1) {
                            //I'm trying to write byte[] into blobstore instead of printing using
                            //System.out.write(buf, 0, len);
                        }

Any advice?

Upvotes: 0

Views: 1221

Answers (2)

Dodo
Dodo

Reputation: 51

Easiest way:

  import com.google.appengine.api.files.FileService;
  import com.google.appengine.api.files.AppEngineFile;
  import com.google.appengine.api.files.FileWriteChannel;
  import com.google.appengine.api.blobstore.BlobKey;
  import com.google.appengine.api.images.ImagesServiceFactory;
  import com.google.appengine.api.images.ServingUrlOptions;
  ...


  // your data in byte[] format
  byte[] data = image.getData();
  /**
   *  MIME Type for
   *  JPG use "image/jpeg" for PNG use "image/png"
   *  PDF use "application/pdf"
   *  see more: https://en.wikipedia.org/wiki/Internet_media_type
   */
  String mimeType = "image/jpeg";

  // save data to Google App Engine Blobstore 
  FileService fileService = FileServiceFactory.getFileService();
  AppEngineFile file = fileService.createNewBlobFile(mimeType); 
  FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
  writeChannel.write(java.nio.ByteBuffer.wrap(data));
  writeChannel.closeFinally();

  // your blobKey to your data in Google App Engine BlobStore
  BlobKey blobKey = fileService.getBlobKey(file);

  // THANKS TO BLOBKEY YOU CAN GET FOR EXAMPLE SERVING URL FOR IMAGES

  // Get the image serving URL (in https:// format)
  String imageUrl =
      ImagesServiceFactory.getImagesService().getServingUrl(
        ServingUrlOptions.Builder.withBlobKey(blobKey
              ).secureUrl(true));

Upvotes: 0

Peter Knego
Peter Knego

Reputation: 80340

Try this:

FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
while ((len = zis.read(buf, 0, buf.length)) != -1) {
    writeChannel. write(ByteBuffer.wrap(buf, 0, len), null);
}

Upvotes: 1

Related Questions