0

我有一个需要将文件从用户计算机上传到服务器的 Java 小程序。我无法添加其他库(例如 com.apache)。是否有这样做的低级方法。目前,我在服务器上有一个 php 文件,其中包含:

    //Sets the target path for the upload.
    $target_path = "spelling/";

    $_FILES = $_POST;
    var_dump($_FILES);

    move_uploaded_file($_FILES["tmp_name"], $target_path . $_FILES["name"]);
?>

目前我的 Java 程序正在通过 POST 向这个 php 文件发送参数。它使用以下代码通过 POST 发送这些参数:

     try {   
        //Creates a new URL containing the php file that writes files on the ec2.
        url = new URL(WEB_ADDRESS + phpFile);
        //Opens this connection and allows for the connection to output.
        connection = url.openConnection();
        connection.setDoOutput(true);

        //Creates a new streamwriter based on the output stream of the connection.
        OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());

        //Writes the parameters to the php file on the ec2 server.
        wr.write(data);
        wr.flush();

        //Gets the response from the server.
        //Creates a buffered input reader from the input stream of the connection.
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;

        //Loops through and reads the response. Loops until reaches null line.
        while ((line = rd.readLine()) != null) {
            //Prints to console.
            System.out.println(line);
        }

        //Closes reader and writer.
        wr.close();
        rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

这适用于 POST 数据,但是当我尝试使用这种方法发送文件时,什么也没有发生(服务器没有响应,文件也没有上传)。如果有人有任何提示,我将不胜感激:)

4

1 回答 1

0

你在用java.net.URLConnection吗?

您可能希望在此页面上获得一些帮助:

http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

这是主要部分:

    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);

但是,您需要让 php 脚本位于您的 applet 所在的同一台服务器上。

于 2013-03-24T04:01:41.757 回答