Uploading a file using HTTP Post and Play! Framework Databinding on Google App engine

Using an http POST and sending to a Play! controller fails if the Controller action declares the request as java.io.File. So doing this would give a null value for the File variable in the controller:

HTML Form:

<form action="@{Application.uploadFile()}" method="POST" enctype="multipart/form-data">
    <input type="text" name="title" size="40"/>
    <input type="file" id="myfile" name="myfile" />
    <input type="submit" value="Send it..." />
</form>

And Controller:

    public static void uploadFile(File myfile, String title) {
    	if (myfile != null) {
    		Logger.info("Got a file");
    	} else {
    		Logger.info("Myfile is empty");
    	}
    	Logger.info("Title: " + title);
    }

To fix this you should not use File but instead use play.data.Upload type as the argument type:

    public static void uploadFile(Upload myfile, String title) {
    	if (myfile != null) {
    		Logger.info("Got a file");
    	} else {
    		Logger.info("Myfile is empty");
    	}
    	Logger.info("Title: " + title);
    }

For the curious the first instance fails on GAE because on GAE file writes are not allowed and the error

java.security.AccessControlException: access denied (java.io.FilePermission…)

is thrown in the Play! method public Map parse(InputStream body)  which tries to save the File to disk.

You can also retrieve the contents by using an undocumented variable in the request. You can obtain a List of Uploads from your controller using

List<Upload> uploads  = (List<Upload>) request.current().args.get("__UPLOADS");

But this is method is hacky and may break in the future.

Advertisements
This entry was posted in Google App Engine, Play framework. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s