Techminded

Ajax File Upload in PlayFramework

Accoring to Google uploading files with Ajax may seems tricky, but it's not. Let's take Valums file upload script that can be downloaded here:

http://valums.com/ajax-upload/

And place it into public/ under the name valums-file-uploader. I'm not spliting files it contains to javascripts, stylesheets etc. to keep distributioin untouched and upgradable. Now we need to chage demo example only a bit:

<div id="file-uploader-demo1">
    <noscript>
        <p>Please enable JavaScript to use file uploader.</p>
        <!-- or put a simple form for upload here -->
    </noscript>
</div>

<script src="/public/valums-file-uploader/fileuploader.js" type="text/javascript"></script>
<script>
    function createUploader(){
        var uploader = new qq.FileUploader({
            element: document.getElementById('file-uploader-demo1'),
            action: '/upload/',
            debug: true
        });
    }
    window.onload = createUploader;
</script>

We should implement also controller method. Assume you have model class 'Media' with JPA's blob field 'file' for file data (or UID)  and string fileName to store original filename:

    public static void upload() throws IOException {
        String filename = params.get("qqfile");
        Media media = new Media(filename);
        media.fileName = filename;
        media.file = new Blob();
        media.file.set(request.body, MimeTypes.getContentType(filename));
        media.save();
        index();
    }

Now write route for upload method and that's it !

Comments