使用 Java 上传和 POST 文件到 PHP 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1314249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:09:34  来源:igfitidea点击:

Upload and POST file to PHP page with Java

javaphppostupload

提问by

I need a way to upload a file and POST it into php page...

我需要一种上传文件并将其发布到 php 页面的方法...

My php page is:

我的 php 页面是:

<?php 
$maxsize = 10485760;
$array_estensioni_ammesse=array('.tmp');
$uploaddir = 'uploads/';
if (is_uploaded_file($_FILES['file']['tmp_name']))
{
    if($_FILES['file']['size'] <= $maxsize)
    {
        $estensione = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], "."), strlen($_FILES['file']['name'])-strrpos($_FILES['file']['name'], ".")));
        if(!in_array($estensione, $array_estensioni_ammesse))
        {
            echo "File is not valid!\n";
        }
        else
        {
            $uploadfile = $uploaddir . basename($_FILES['file']['name']); 
            echo "File ". $_FILES['file']['name'] ." uploaded successfully.\n"; 
            if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile))
            {
                echo "File is valid, and was successfully moved.\n";
            } 
            else 
                print_r($_FILES); 
        }
    }
    else
        echo "File is not valid!\n";
}
else
{ 
    echo "Upload Failed!!!"; 
    print_r($_FILES);
} 
?>

and i use this java code in my desktop application:

我在我的桌面应用程序中使用这个 java 代码:

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.setRequestMethod("POST");
        OutputStream os = httpUrlConnection.getOutputStream();
        Thread.sleep(1000);
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream("tmpfile.tmp"));

        long totalByte = fis.available();
        long byteTrasferred = 0;
        for (int i = 0; i < totalByte; i++) {
            os.write(fis.read());
            byteTrasferred = i + 1;
        }

        os.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                httpUrlConnection.getInputStream()));

        String s = null;
        while ((s = in.readLine()) != null) {
            System.out.println(s);
        }
        in.close();
        fis.close();

But I receive always the "Upload Failed!!!" message.

但我总是收到“上传失败!!!” 信息。

回答by Byron Whitlock

You are not using the correct HTML file upload semantics. You are just posting a bunch of data to the url.

您没有使用正确的 HTML 文件上传语义。您只是将一堆数据发布到网址。

You have 2 option here:

您在这里有 2 个选择:

  • You can keep the java code as-is, and change the php code to just read the raw POST as a file.
  • Change the java code to do a real file upload possibly using a common library.
  • 您可以按原样保留 java 代码,并将 php 代码更改为仅将原始 POST 作为文件读取。
  • 更改 java 代码以执行可能使用公共库的真实文件上传。

I'd recommend changing the java code to do this in a standards compliant way.

我建议更改 java 代码以符合标准的方式执行此操作。

回答by Chris Thompson

You need to use a form-multipart encoded post for PHP to be able to read it the way you are attempting. Thiswebsite outlines a good way to do it and has links to libraries that can help you out.

您需要为 PHP 使用表单多部分编码的帖子,以便能够按照您尝试的方式阅读它。 网站概述了一个很好的方法,并提供了可以帮助您解决问题的图书馆链接。

回答by Daniil

All above answers are 100% correct. You can also use plain sockets, in which case your method would look like this:

以上所有答案100%正确。您还可以使用普通套接字,在这种情况下,您的方法将如下所示:

        // Compose the request header
        StringBuffer buf = new StringBuffer();
        buf.append("POST ");
        buf.append(uploader.getUploadAction());
        buf.append(" HTTP/1.1\r\n");
        buf.append("Content-Type: multipart/form-data; boundary=");
        buf.append(boundary);
        buf.append("\r\n");
        buf.append("Host: ");
        buf.append(uploader.getUploadHost());
        buf.append(':');
        buf.append(uploader.getUploadPort());
        buf.append("\r\n");
        buf.append("Connection: close\r\n");
        buf.append("Cache-Control: no-cache\r\n");

        // Add cookies
        List cookies = uploader.getCookies();
        if (!cookies.isEmpty())
            {
                buf.append("Cookie: ");
                for (Iterator iterator = cookies.iterator(); iterator.hasNext(); )
                    {
                        Parameter parameter = (Parameter)iterator.next();

                        buf.append(parameter.getName());
                        buf.append('=');
                        buf.append(parameter.getValue());

                        if (iterator.hasNext())
                            buf.append("; ");
                    }

                buf.append("\r\n");
            }

        buf.append("Content-Length: ");

        // Request body
        StringBuffer body = new StringBuffer();
        List fields = uploader.getFields();
        for (Iterator iterator = fields.iterator(); iterator.hasNext();)
            {

                Parameter parameter = (Parameter) iterator.next();

                body.append("--");
                body.append(boundary);
                body.append("\r\n");
                body.append("Content-Disposition: form-data; name=\"");
                body.append(parameter.getName());
                body.append("\"\r\n\r\n");
                body.append(parameter.getValue());
                body.append("\r\n");
            }

        body.append("--");
        body.append(boundary);
        body.append("\r\n");
        body.append("Content-Disposition: form-data; name=\"");
        body.append(uploader.getImageFieldName());
        body.append("\"; filename=\"");
        body.append(file.getName());
        body.append("\"\r\n");
        body.append("Content-Type: image/pjpeg\r\n\r\n");

        String boundary = "WHATEVERYOURDEARHEARTDESIRES";
        String lastBoundary = "\r\n--" + boundary + "--\r\n";
        long length = file.length() + (long) lastBoundary.length() + (long) body.length();
        long total = buf.length() + body.length();

        buf.append(length);
        buf.append("\r\n\r\n");

        // Upload here
        InetAddress address = InetAddress.getByName(uploader.getUploadHost());
        Socket socket = new Socket(address, uploader.getUploadPort());
        try
            {
                socket.setSoTimeout(60 * 1000);
                uploadStarted(length);

                PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
                out.print(buf);
                out.print(body);

                // Send the file
                byte[] bytes = new byte[1024 * 65];
                int size;
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                try
                    {
                        while ((size = in.read(bytes)) > 0)
                            {
                                total += size;
                                out.write(bytes, 0, size);
                                transferred(total);
                            }
                    }
                finally
                    {
                        in.close();
                    }

                out.print(lastBoundary);
                out.flush();

                // Read the response
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (reader.readLine() != null);
            }
        finally
            {
                socket.close();
            }

回答by Lauri Lehtinen

I realize this is a bit old but I just posted an answer to a similar questionthat should be applicable here as well. It includes code similar to Daniil's, but uses HttpURLConnection instead of a Socket.

我意识到这有点旧,但我刚刚发布了一个类似问题答案,答案也适用于此。它包含类似于 Daniil 的代码,但使用 HttpURLConnection 而不是 Socket。

回答by user622169

This is an old thread, but for the benefit of others, here is a fully workingexample of exactly what the op asks for:

这是一个旧线程,但为了其他人的利益,这里有一个完整的示例,说明操作所要求的内容:

PHP server code:

PHP服务器代码:

<?php 

$target_path = "uploads/"; 

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
}

?> 

Java client code:

Java客户端代码:

import java.io.OutputStream;
import java.io.InputStream;
import java.net.URLConnection;
import java.net.URL;
import java.net.Socket;

public class Main {
    private final String CrLf = "\r\n";

    public static void main(String[] args) {
        Main main = new Main();
        main.httpConn();
    }

    private void httpConn() {
        URLConnection conn = null;
        OutputStream os = null;
        InputStream is = null;

        try {
            URL url = new URL("http://localhost/test/post.php");
            System.out.println("url:" + url);
            conn = url.openConnection();
            conn.setDoOutput(true);

            String postData = "";

            InputStream imgIs = getClass().getResourceAsStream("/test.jpg");
            byte[] imgData = new byte[imgIs.available()];
            imgIs.read(imgData);

            String message1 = "";
            message1 += "-----------------------------4664151417711" + CrLf;
            message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\""
                    + CrLf;
            message1 += "Content-Type: image/jpeg" + CrLf;
            message1 += CrLf;

            // the image is sent between the messages in the multipart message.

            String message2 = "";
            message2 += CrLf + "-----------------------------4664151417711--"
                    + CrLf;

            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=---------------------------4664151417711");
            // might not need to specify the content-length when sending chunked
            // data.
            conn.setRequestProperty("Content-Length", String.valueOf((message1
                    .length() + message2.length() + imgData.length)));

            System.out.println("open os");
            os = conn.getOutputStream();

            System.out.println(message1);
            os.write(message1.getBytes());

            // SEND THE IMAGE
            int index = 0;
            int size = 1024;
            do {
                System.out.println("write:" + index);
                if ((index + size) > imgData.length) {
                    size = imgData.length - index;
                }
                os.write(imgData, index, size);
                index += size;
            } while (index < imgData.length);
            System.out.println("written:" + index);

            System.out.println(message2);
            os.write(message2.getBytes());
            os.flush();

            System.out.println("open is");
            is = conn.getInputStream();

            char buff = 512;
            int len;
            byte[] data = new byte[buff];
            do {
                System.out.println("READ");
                len = is.read(data);

                if (len > 0) {
                    System.out.println(new String(data, 0, len));
                }
            } while (len > 0);

            System.out.println("DONE");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Close connection");
            try {
                os.close();
            } catch (Exception e) {
            }
            try {
                is.close();
            } catch (Exception e) {
            }
            try {

            } catch (Exception e) {
            }
        }
    }
}

you can figure out how to adapt it for your site, but I have tested the above code and it works. I can't take credit for it though >> See Original Post

您可以弄清楚如何为您的网站调整它,但我已经测试了上面的代码并且它有效。虽然我不能相信它 >>见原帖

回答by BoltzmannBrain

Even though the thread is very old, there may still be someone around looking for a more easy way to solve this problem (like me :))

尽管该线程很旧,但可能仍然有人在寻找解决此问题的更简单方法(例如我:))

After some research I found a way to uplaod a file without changing the original poster's Java-Code. You just have to use the following PHP-code:

经过一番研究,我找到了一种无需更改原始发布者的 Java 代码即可上传文件的方法。您只需要使用以下 PHP 代码:

<?php
  $filename="abc.xyz";
  $fileData=file_get_contents('php://input');
  $fhandle=fopen($filename, 'wb');
  fwrite($fhandle, $fileData);
  fclose($fhandle);
  echo("Done uploading");
?>

This code is just fetching the raw data sent by the java-application and writing it into a file. There is, however one problem: You dont get the original filename, so you have to transmit it somehow else.

这段代码只是获取 java 应用程序发送的原始数据并将其写入文件。但是有一个问题:您没有获得原始文件名,因此您必须以其他方式传输它。

I solved this problem by using a GET-Parameter, which makes a little change in the Java-code necessary:

我通过使用 GET 参数解决了这个问题,这需要对 Java 代码进行一些更改:

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();

changes to

更改为

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php?filename=abc.def").openConnection();

In your PHP-script you change the line

在您的 PHP 脚本中,您更改了该行

$filename="abc.xyz";

to

$filename=$_GET['filename'];

This solution doesn't use any external librarys and seems to me much more simple than some of the other posted ones...

这个解决方案不使用任何外部库,在我看来比其他一些发布的要简单得多......

Hope I could help anyone:)

希望我可以帮助任何人:)