【问题标题】:JavaFX create file on the server sideJavaFX 在服务器端创建文件
【发布时间】:2023-03-04 08:36:01
【问题描述】:

我的 javaFX 应用程序在 Web 服务器 (wamp) 上运行,客户端通过浏览器访问此应用程序。我想在服务器端创建一个 xml 文件。我怎样才能做到这一点?因为目前如果我使用例如“/Users/username/Desktop”的路径,它将在客户端桌面上创建文件。我想在服务器桌面上创建这个文件。 我在 netbeans 7.2.1 上使用 javaFX 2.2

对不起我的英语不好!谢谢!

【问题讨论】:

  • 如果应用程序“在网络服务器(wamp)上运行”,它如何“在客户端桌面上创建文件”?
  • @foampile 我不太了解 JavaFX,但我认为客户端执行 html 文件中包含的 jnlp 文件。我对这种语言真的很陌生,但是如果我使用服务器目录的路径,我会遇到异常“找不到目录”,因为运行时正在检查客户端的路径,我猜...
  • @foampile - 在这种情况下,客户端需要从网络服务器获取它,并将其存储在本地文件系统的某个位置。

标签: java javafx-2 javafx


【解决方案1】:

看起来 wamp 是一个基于 php 的服务器。在这种情况下,服务器组件将需要一些 php 脚本来处理上传。 w3schools has a sample script for uploading via php(我不认可这个脚本,因为我从未使用过它,也没有使用过 php - 我只是提供它作为参考)。

文件上传的 w3schools 教程使用 html 将文件数据发布到服务器。使用 JavaFX,您将改为使用 Java 对文件发布进行编码。 JavaFX 客户端中的 Java 部分将需要使用多部分表单 post 将文件从客户端发送到服务器。 apache httpclient 之类的东西可以做到这一点。这篇文章中有端到端解决方案的示例代码:How to upload a file using Java HttpClient library working with PHP

【讨论】:

    【解决方案2】:

    您的 JavaFX 应用程序需要与您的 Web 服务进行通信。在这种情况下,我认为它是您网站上的一个简单表格。为此,您的客户端需要使用 GET(不太灵活)或 POST(更灵活)方法来上传稍后将由您的 PHP 脚本处理的文件。

    正如jewelsea 所建议的,Apache HttpClient 可以为您完成这项工作。但是,如果您像我一样不喜欢为简单的事情添加依赖项,您可能会决定卷起袖子,像我一样实现 HttpPost 类:

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

    如您所见,有很多地方需要改进。该类使用 HttpURLConnection 并使用 POST 方法上传文件。我用它来上传图片到我的一个网站。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-29
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多