Skip to content

Instantly share code, notes, and snippets.

@codephillip
Forked from raffaeleguidi/Application.java
Created March 2, 2017 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codephillip/a6ab86dbb2801a3ea1d367fb047d81e1 to your computer and use it in GitHub Desktop.
Save codephillip/a6ab86dbb2801a3ea1d367fb047d81e1 to your computer and use it in GitHub Desktop.
A simple file upload and renderBinary example using Play! 1.2.3 and GAE (google appengine) 1.5.6
package controllers;
import play.*;
import play.data.Upload;
import play.db.Model.BinaryField;
import play.libs.MimeTypes;
import play.mvc.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import com.google.appengine.api.datastore.Blob;
import com.google.apphosting.utils.remoteapi.RemoteApiPb.Response;
import models.*;
public class Application extends Controller {
public static void index() {
List images = Picture.all().fetch();
render(images);
}
public static void uploadPicture(Upload data) {
Picture picture = new Picture();
Logger.info(data.getContentType());
Logger.info(data.getFieldName());
Logger.info(data.getFileName());
picture.contentType = data.getContentType();
picture.fileName = data.getFileName();
picture.file = data.asBytes();
picture.save();
Logger.info("saving id=%s", picture.id);
index();
}
public static void show(Long id) {
Logger.info("loading id=%s", id);
Picture picture = Picture.findByKey(id);
response.setContentTypeIfNotSet(picture.contentType);
renderBinary(new ByteArrayInputStream(picture.file), picture.file.length);
}
}
#{extends 'main.html' /}
#{set title:'Home' /}
#{list items:images, as:'image'}
<a href="@{show(image.id)}">
<img border="0" src="@{show(image.id)}" width="50px" />
${image.fileName}
</a>
<br />
#{/list}
<br />
#{form @Application.uploadPicture(), enctype:'multipart/form-data'}
<input type="file" name="data" />
<input type="submit" name="submit" value="Aggiungi" />
#{/form}
package models;
import siena.*;
@Table("picture")
public class Picture extends Model {
@Id(Generator.AUTO_INCREMENT)
public Long id;
public byte[] file;
public String fileName;
public String contentType;
public static Query<Picture> all() {
return Model.all(Picture.class);
}
public static Picture findByKey(Long id) {
return all().getByKey(id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment