Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java将文件上载并发布到PHP页面_Java_Php_Post_Upload - Fatal编程技术网

使用Java将文件上载并发布到PHP页面

使用Java将文件上载并发布到PHP页面,java,php,post,upload,Java,Php,Post,Upload,我需要一种方法来上传一个文件,并张贴到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) { $est

我需要一种方法来上传一个文件,并张贴到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);
} 
?>

我在桌面应用程序中使用以下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();
HttpURLConnection HttpURLConnection=(HttpURLConnection)新URL(“http://www.mypage.org/upload.php”).openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestMethod(“POST”);
OutputStream os=httpUrlConnection.getOutputStream();
睡眠(1000);
BufferedInputStream fis=新的BufferedInputStream(新文件输入流(“tmpfile.tmp”);
long totalByte=fis.available();
long byteTrasferred=0;
for(int i=0;i

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

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

您在这里有两个选项:

  • 您可以保持java代码不变,并将php代码更改为仅将原始文章作为文件读取
  • 更改java代码以执行真正的文件上载,可能需要使用

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

您需要使用表单多部分编码的post for PHP,以便能够以您尝试的方式读取它。该网站概述了一种很好的方法,并提供了一些图书馆链接,可以帮助您解决问题。

以上所有答案都是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();
            }

我意识到这有点旧,但我刚刚发布了一个应该也适用于这里的。它包含与Danil类似的代码,但使用HttpURLConnection而不是套接字。

这是一个旧线程,但为了其他线程的利益,这里有一个完全工作的示例,正好说明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!"; 
}

?> 

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) {
            }
        }
    }
}
import java.io.OutputStream;
导入java.io.InputStream;
导入java.net.URLConnection;
导入java.net.URL;
导入java.net.Socket;
公共班机{
专用最终字符串CrLf=“\r\n”;
公共静态void main(字符串[]args){
Main Main=新Main();
main.httpConn();
}
私有无效httpConn(){
URLConnection conn=null;
OutputStream os=null;
InputStream=null;
试一试{
URL=新URL(“http://localhost/test/post.php");
System.out.println(“url:+url”);
conn=url.openConnection();
连接设置输出(真);
字符串postData=“”;
InputStream imgIs=getClass().getResourceAsStream(“/test.jpg”);
字节[]imgData=新字节[imgIs.available()];
imgIs.read(imgData);
字符串message1=“”;
信息1+=“-------------------------------4664151417711”+CrLf;
message1+=“内容配置:表单数据;名称=\“uploadedfile\”文件名=\“test.jpg\”
+CrLf;
message1+=“内容类型:图像/jpeg”+CrLf;
message1+=CrLf;
//图像在多部分消息中的消息之间发送。
字符串message2=“”;
message2+=CrLf+“---------------------------------------4664151417711--”
+CrLf;
conn.setRequestProperty(“内容类型”,
“多部分/表单数据;边界=------------------------------------4664151417711”);
//发送分块时可能不需要指定内容长度
//数据。
conn.setRequestProperty(“内容长度”,String.valueOf((message1
.length()+message2.length()+imgData.length));
System.out.println(“开放操作系统”);
os=conn.getOutputStream();
System.out.println(message1);
write(message1.getBytes());
//发送图像
int指数=0;
int size=1024;
做{
System.out.println(“写入:+索引”);
如果((索引+大小)>imgData.length){
大小=imgData.length-索引;
}
写入(imgData、索引、大小);
指数+=大小;
}而(指数0){
System.out.println(新字符串(数据,0,len));
}
}而(len>0);
系统输出打印项次(“完成”);
}捕获(例外e){
e、 printStackTrace();
}最后{
System.out.println(“紧密连接”);
试一试{
os.close();
}捕获(例外e){
}
试一试{
is.close();
}捕获(例外e){
}
试一试{
}捕获(例外e){
}
}
}
}

您可以找出如何使其适应您的站点,但我已经测试了上述代码,它可以正常工作。尽管线程非常陈旧,但我不能因此而受到赞扬,可能仍有人在寻找更简单的方法来解决此问题
<?php
  $filename="abc.xyz";
  $fileData=file_get_contents('php://input');
  $fhandle=fopen($filename, 'wb');
  fwrite($fhandle, $fileData);
  fclose($fhandle);
  echo("Done uploading");
?>
HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php?filename=abc.def").openConnection();
$filename="abc.xyz";
$filename=$_GET['filename'];