1

I have my javaFX application running on a web server (wamp) and the client access to this app by a browser. I want to create an xml file on the server side. How can i do that? Because at the moment if i use a path for example "/Users/username/Desktop" it will create the file on the client Desktop. I want to create this file on the server desktop. I'm using javaFX 2.2 on netbeans 7.2.1

Sorry for my bad English! Thank you!

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
beny1700
  • 284
  • 1
  • 4
  • 10
  • 1
    if the app is "running on a web server (wamp)", how can it "create the file on the client Desktop"? – amphibient Jan 29 '13 at 19:14
  • @foampile I don't know JavaFX very well but I think the client execute the jnlp file included in the html file. I am realy new to this language but if I use a path to a server directory I have an exception "directory not found" because the runtime is checking the path on the client side I guess... – beny1700 Jan 29 '13 at 20:00
  • @foampile - client needs to fetch it from the web-server in that case, and store it somewhere on the local filesystem. – DejanLekic Jan 30 '13 at 13:43

2 Answers2

3

Your JavaFX application needs to communicate with your web service. In this case i presume it is a simple form on your web-site. In order to do so your client needs to use either GET (less flexible) or POST (more flexible) method to upload a file that will later be handled by your PHP script.

As suggested by jewelsea, Apache HttpClient can do the job for you. However, if you, like me, do not like adding dependencies for simple things, you may decide to roll-up your sleeves and implement the HttpPost class like I did:

/**
 * Project: jlib
 * Version: $Id: HttpPost.java 463 2012-09-17 10:58:04Z dejan $
 * License: Public Domain
 * 
 * Authors (in chronological order):
 *   Dejan Lekic - http://dejan.lekic.org
 * Contributors (in chronological order):
 *   -
 */

package co.prj.jlib;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A class that uses HttpURLConnection to do a HTTP post. 
 * 
 * The main reason for this class is to have a simple solution for uploading files using the PHP file below:
 * 
 * Example:
 * 
 * <pre>
 *  <?php
 *  // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
 *  // of $_FILES.
 *
 *  $uploaddir = '/srv/www/lighttpd/example.com/files/';
 *  $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
 *
 *  echo '<pre>';
 *  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
 *      echo "File is valid, and was successfully uploaded.\n";
 *      } else {
 *          echo "Possible file upload attack!\n";
 *      }
 *
 *      echo 'Here is some more debugging info:';
 *      print_r($_FILES);
 *
 *      print "</pre>";
 *  }        
 *  ?>
 *
 * </pre>
 * 
 * TODO:
 *   - Add support for arbitrary form fields.
 *   - Add support for more than just one file.
 *   - Allow for changing of the boundary
 * 
 * @author dejan
 */
public class HttpPost {
    private final String crlf = "\r\n";
    private URL url;
    private URLConnection urlConnection;
    private OutputStream outputStream;
    private InputStream inputStream;
    private String[] fileNames;
    private String output;
    private String boundary;
    private final int bufferSize = 4096;

    public HttpPost(URL argUrl) {
        url = argUrl;
        boundary = "---------------------------4664151417711";
    }

    public void setFileNames(String[] argFiles) {
        fileNames = argFiles;
    }

    public void post() {
        try {
            System.out.println("url:" + url);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            String postData = "";
            String fileName = fileNames[0];
            InputStream fileInputStream = new FileInputStream(fileName);

            byte[] fileData = new byte[fileInputStream.available()];
            fileInputStream.read(fileData);

            // ::::: PART 1 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            String part1 = "";
            part1 += "--" + boundary + crlf;
            File f = new File(fileNames[0]);
            fileName = f.getName(); // we do not want the whole path, just the name
            part1 += "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" 
                    + crlf;

            // CONTENT-TYPE
            // TODO: add proper MIME support here
            if (fileName.endsWith("png")) {
                part1 += "Content-Type: image/png" + crlf;
            } else {
                part1 += "Content-Type: image/jpeg" + crlf;
            }

            part1 += crlf;
            System.out.println(part1);
            // File's binary data will be sent after this part

            // ::::: PART 2 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            String part2 = crlf + "--" + boundary + "--" + crlf;



            System.out.println("Content-Length" 
                    +  String.valueOf(part1.length() + part2.length() + fileData.length));
            urlConnection.setRequestProperty("Content-Length", 
                    String.valueOf(part1.length() + part2.length() + fileData.length));


            // ::::: File send ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            outputStream = urlConnection.getOutputStream();
            outputStream.write(part1.getBytes());

            int index = 0;
            int size = bufferSize;
            do {
                System.out.println("wrote " + index + "b");
                if ((index + size) > fileData.length) {
                    size = fileData.length - index;
                }
                outputStream.write(fileData, index, size);
                index += size;
            } while (index < fileData.length);
            System.out.println("wrote " + index + "b");

            System.out.println(part2);
            outputStream.write(part2.getBytes());
            outputStream.flush();

            // ::::: Download result into the 'output' String :::::::::::::::::::::::::::::::::::::::::::::::
            inputStream = urlConnection.getInputStream();
            StringBuilder sb = new StringBuilder();
            char buff = 512;
            int len;
            byte[] data = new byte[buff];
            do {

                len = inputStream.read(data);

                if (len > 0) {
                    sb.append(new String(data, 0, len));
                }
            } while (len > 0);
            output = sb.toString();

            System.out.println("DONE");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Close connection");
            try {
                outputStream.close();
            } catch (Exception e) {
                System.out.println(e);
            }
            try {
                inputStream.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    } // post() method

    public String getOutput() {
        return output;
    }

    public static void main(String[] args) {
        // Simple test, let's upload a picture
        try {
            HttpPost httpPost = new HttpPost(new URL("http://www.example.com/file.php"));
            httpPost.setFileNames(new String[]{ "/home/dejan/work/ddn-100x46.png" });
            httpPost.post();
            System.out.println("=======");
            System.out.println(httpPost.getOutput());
        } catch (MalformedURLException ex) {
            Logger.getLogger(HttpPost.class.getName()).log(Level.SEVERE, null, ex);
        }
    } // main() method

} // HttpPost class

As you can see, there are many places for improvements. This class uses HttpURLConnection and uses the POST method to upload file. I use it to upload pictures to one of my web-sites.

DejanLekic
  • 18,787
  • 4
  • 46
  • 77
1

Looks like wamp is a php based server. In which case the server component will need some php script to handle the upload. w3schools has a sample script for uploading via php (I don't endorse this script, as I have never used it nor php - I just offer it as a reference).

The w3schools tutorial for file upload uses html to post file data to the server. With JavaFX you will instead code the file post in Java. The Java portion in the JavaFX client will need use a multi-part form post to send the file from the client to the server. Something like the apache httpclient is able to do this. There is sample code for an end to end solution in this post: How to upload a file using Java HttpClient library working with PHP.

Community
  • 1
  • 1
jewelsea
  • 150,031
  • 14
  • 366
  • 406