投稿‎ > ‎

Google Apps Engineでイメージ保存、公開

posted Dec 26, 2014, 8:44 PM by Zhang Wenxu
package jp.btsol.products.plugins.updatesites;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;
@SuppressWarnings("serial")
public class ImageReceiverServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(ImageReceiverServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
log.info("ImageReceiverServlet working...");
String imageUrl = serveImage(req);
resp.setContentType("text/plain");
resp.getWriter().print(imageUrl);
}
private String serveImage(HttpServletRequest req) throws IOException{
//POSTを読込むため、InputStreamオブジェクトをゲット
InputStream body = req.getInputStream();
//byte列に変換する
byte[] bytes = IOUtils.toByteArray(body);
/**
*  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
*/
//イメージとして、Google Blobに保存する
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(bytes));
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));
log.info("url: " + imageUrl);
return imageUrl;
}
}

Comments