使用Java将文件上传到POST页面

6 php java upload post

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

我的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);
} 
?>
Run Code Online (Sandbox Code Playgroud)

我在我的桌面应用程序中使用此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"));

        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();
Run Code Online (Sandbox Code Playgroud)

但我总是收到"上传失败!!!" 信息.

小智 19

虽然线程很老,但仍然有人在寻找更简单的方法来解决这个问题(比如我:))

经过一些研究,我发现了一种在不改变原始海报的Java代码的情况下上传文件的方法.您只需使用以下PHP代码:

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

这段代码只是获取java-application发送的原始数据并将其写入文件.但是有一个问题:你没有得到原始文件名,所以你必须以其他方式传输它.

我通过使用GET参数解决了这个问题,这使得必要的Java代码发生了一些变化:

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();
Run Code Online (Sandbox Code Playgroud)

改变为

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

在PHP脚本中,您可以更改该行

$filename="abc.xyz";
Run Code Online (Sandbox Code Playgroud)

$filename=$_GET['filename'];
Run Code Online (Sandbox Code Playgroud)

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

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


小智 13

这是一个旧线程,但为了其他人的利益,这里有一个完全正常的例子,正是op要求的:

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!"; 
}

?> 
Run Code Online (Sandbox Code Playgroud)

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) {
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以弄清楚如何为你的网站调整它,但我测试了上面的代码,它的工作原理.我不能相信它虽然>> 见原帖


Byr*_*ock -1

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

您在这里有 2 个选择:

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