2013-01-29 5 views
1

웹 브라우저 (wamp)에서 실행중인 javaFX 응용 프로그램과 클라이언트가이 응용 프로그램을 브라우저에서 액세스하도록했습니다. 나는 서버 쪽에서 XML 파일을 만들고 싶다. 내가 어떻게 할 수 있니? 왜냐하면 순간에 "/ Users/username/Desktop"과 같은 경로를 사용하기 때문에 클라이언트 데스크톱에 파일을 생성하게됩니다. 서버 바탕 화면에서이 파일을 만들고 싶습니다. netbeans에서 javaFX 2.2를 사용하고 있습니다. 7.2.1JavaFX 서버 측 파일 만들기

나쁜 영어로 죄송합니다! 고맙습니다!

+1

앱이 "웹 서버 (Wamp)에서 실행 중"인 경우 어떻게 클라이언트 데스크톱에서 파일을 만들 수 있습니까? – amphibient

+0

@foampile JavaFX를 잘 모르지만 클라이언트가 html 파일에 포함 된 jnlp 파일을 실행한다고 생각합니다. 나는이 언어에 새로운 것이지만 서버 디렉토리에 대한 경로를 사용하는 경우 런타임에서 클라이언트 측의 경로를 확인하기 때문에 "디렉토리를 찾을 수 없음"예외가 발생합니다. – beny1700

+0

@foampile - 클라이언트가 가져와야 함 이 경우 웹 서버에서 가져 와서 로컬 파일 시스템의 어딘가에 저장하십시오. – DejanLekic

답변

1

보이는 wamp는 PHP 기반 서버입니다. 어떤 경우에는 서버 구성 요소가 업로드를 처리 할 PHP 스크립트가 필요합니다. w3schools has a sample script for uploading via php (필자는 한번도이 스크립트를 사용하지 않았기 때문에이 스크립트를지지하지 않습니다. 단지 PHP를 참고로 제공합니다).

파일 업로드를위한 w3schools 튜토리얼은 html을 사용하여 파일 데이터를 서버에 게시합니다. JavaFX를 사용하면 대신 Java에서 파일 게시를 코딩합니다. JavaFX 클라이언트의 Java 부분은 클라이언트에서 서버로 파일을 보내려면 여러 부분으로 된 양식 게시물을 사용해야합니다. apache httpclient과 같은 것을이 작업을 수행 할 수 있습니다. 이 게시물의 종단 간 솔루션을위한 샘플 코드는 How to upload a file using Java HttpClient library working with PHP입니다.

2

JavaFX 응용 프로그램이 웹 서비스와 통신해야합니다. 이 경우에는 귀하의 웹 사이트에 간단한 양식이라고 가정합니다. 이렇게하기 위해서 클라이언트는 나중에 PHP 스크립트에 의해 처리 될 파일을 업로드하기 위해 GET (덜 유연한) 또는 POST (보다 유연한) 방법을 사용해야합니다.

jewelsea에서 제안한대로 Apache HttpClient가 작업을 수행 할 수 있습니다. 당신이 볼 수 있듯이

/** 
* 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 

, 많은 사람들이있다 : 당신이 나 같은 간단한 것들에 대한 종속성을 추가 좋아하지 않는 경우, 당신은 당신의 소매를-말아서 내가 한 것처럼 HttpPost를 구현하기로 결정할 수있다 개선을위한 장소. 이 클래스는 HttpURLConnection을 사용하고 POST 메서드를 사용하여 파일을 업로드합니다. 내 웹 사이트 중 하나에 사진을 업로드하는 데 사용합니다.