JavaFX – Upload File

Bookmark and Share

One of the previous post had a sample to download large files using JavaFX. It relies on HttpRequest attribute sink to specify the output file location. Similarly we can use source attribute for uploading a file.

I have written a simple UploadServlet to receive the file content and save at <user.home>/JavaFXDownloads/ location.

Relevant part of JavaFX client code is given below..

def uploadServletURL = 

def urlConverter = URLConverter{ };
def encodedServletURL = urlConverter.encodeURL(

def httpRequest: HttpRequest = HttpRequest {

    location: encodedServletURL    
    source: new
    method: HttpRequest.POST

    headers: [
        HttpHeader {
            name: HttpHeader.CONTENT_TYPE
            value: "multipart/form-data"

Name of file is passed as argument to upload servlet. This URL is encoded using URLConverter. The file to be uploaded is assigned to source attribute. Http content-type is set to “multipart/form-data”. You can host the UploadServlet – server – code in any webserver such as Tomcat, Glassfish etc. Value of uploadServletURL in JavaFX client must be updated to point to this servlet URL.

I found another sample code Multipart HTTP file upload with JavaFX which demonstrates alternate approach.

Try it out and let me know feedback..


JavaFX – Upload and Download Large Files

We can upload or download large files using new HttpRequest attributes available in JavaFX 1.2.

HttpRequest has input and onInput attributes that provides InputStream which can be used to download data. This stream supports mark, reset, available, skip etc. But to support this HttpRequest buffers the data. Due to this buffering it was not possible to use this approach to download large files.

JavaFX 1.2 introduce two new attributes – source (InputStream) and sink (OutputStream). If we set sink attribute, we can directly download the content of stream without buffering. Also with source we can upload the content. Eg: By setting it to FileInputStream. When source or sink attribute is used, corresponding input, onInput, output, onOutput will not be functional.

For Applet mode, click on above image

For standalone mode

The application downloads a larger version of the photo. I took it from Somnathpur using Nikon Coolpix! 🙂

function downloadFile(url , outputFile) {

    def getRequest: HttpRequest = HttpRequest {

        location: url
        sink: new

        onToRead: function(bytes: Long) {
            toRead = bytes;

        onRead: function(bytes: Long) {
            read = bytes;
            println("onRead - {read * 100/toRead}%");

        onDone: function() { println("onDone") }


In above sample, sink is assigned to a FileOutputStream. So all the content will be directly written to file without buffering. Note: For making the application compatible with mobile or other platforms we will have to use only subset of package. Example: MID Profile Core API.