@RequestMapping(value = "/ajax/uploadWelcomeImage", method = RequestMethod.POST)
@ResponseBody
public String uploadWelcomeImage(@RequestParam("id") long id,
HttpServletRequest request) throws IOException, ServletException {
byte[] bytes = IOUtils.toByteArray(request.getInputStream());
Key parentKey = KeyFactory.createKey(ParentClass.class.getSimpleName(),
id);
String blobKey = imageService.saveImageToBlobStore(bytes);
imageService.save(blobKey, parentKey);
return "{success:true, id:\"" + blobKey + "\"}";
}
@Transactional
public String saveImageToBlobStore(byte[] bytes) {
// Get a file service
FileService fileService = FileServiceFactory.getFileService();
// Create a new Blob file with mime-type "text/plain"
AppEngineFile file = null;
try {
file = fileService.createNewBlobFile("image/jpeg");
} catch (IOException e) {
e.printStackTrace();
}
// Open a channel to write to it
boolean lock = true;
FileWriteChannel writeChannel = null;
try {
writeChannel = fileService.openWriteChannel(file, lock);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (FinalizationException e) {
e.printStackTrace();
} catch (LockException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// This time we write to the channel using standard Java
try {
writeChannel.write(ByteBuffer.wrap(bytes));
} catch (IOException e) {
e.printStackTrace();
}
// Now finalize
try {
writeChannel.closeFinally();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Now read from the file using the Blobstore API
BlobKey blobKey = fileService.getBlobKey(file);
while (blobKey == null) { //this is hacky, but necessary as sometimes the blobkey isn't available right away
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
blobKey = fileService.getBlobKey(file);
}
// return
return blobKey.getKeyString();
}
public void save(String imageFileBlobKey, Key parentKey) {
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Entity imageFileEntity = new Entity("ImageFile", parentKey);
imageFileEntity.setProperty("blobKey", imageFileBlobKey);
datastore.put(imageFileEntity);
}
Robert
> --
> You received this message because you are subscribed to the Google Groups
> "Google App Engine" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/google-appengine/-/HQPIJdRNp7EJ.
> To post to this group, send email to google-a...@googlegroups.com.
> To unsubscribe from this group, send email to
> google-appengi...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/google-appengine?hl=en.
>