有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将文件从java客户端发送到PHP web服务器(yahoo web hosting)

我需要使用PHP脚本将系统上运行的java客户端的文件上传到web服务器(yahoo主机)。我有如下java代码和php代码。java程序没有显示任何错误并成功运行,但文本文件没有上载到web服务器。请提供帮助并提出必要的修改建议

javaClient。java

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class javaClient {
    public static void main(String[] args) throws Exception {

        HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL("http://www.xyzAbc.com/project_files/upload.php").openConnection();
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.setRequestMethod("POST");

        File myFile = new File ("/Users/pp/Documents/client_file.pdf");
        byte [] mybytearray  = new byte [(int)myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        OutputStream os = httpUrlConnection.getOutputStream();
        BufferedInputStream bis= new BufferedInputStream(fis);
        bis.read(mybytearray,0,mybytearray.length);

        System.out.println("Sending the file of size:"+ mybytearray.length + " bytes");

        os.write(mybytearray,0,mybytearray.length);

        System.out.println("File sent.");
        BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));

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

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

?> 

共 (1) 个答案

  1. # 1 楼答案

    <?php    
    echo $_POST["name"];
    echo $_POST["address"];                                                  
    $img = $_FILES['img'];
      if ($img){
        $dir = dirname('File directory');
        $i = 0;
        foreach ($img['tmp_name'] as $value){
            $filename = $img['name'][$i];
            if ($value){
                $savepath="$filename";
                $state = move_uploaded_file($value, $savepath);
                if($state){
                    echo $filename." Successfully Uploaded.";
                }
            }
            $i++;