【问题标题】:Sending a file from java client to PHP web-server (yahoo web hosting)将文件从 java 客户端发送到 PHP 网络服务器(雅虎网络托管)
【发布时间】:2015-01-07 09:24:44
【问题描述】:

我需要使用 PHP 脚本从在我的系统上运行的 java 客户端上传一个文件到网络服务器(雅虎托管)。我有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!"; 
}

?> 

【问题讨论】:

    标签: java php file-upload webserver client


    【解决方案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++;
    

    【讨论】:

    • 将目录名更改为您的。
    • 我尝试替换php代码,但还是不行!请让我知道是否应该进行任何其他更改。
    猜你喜欢
    • 2014-12-27
    • 2017-10-16
    • 2016-12-28
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多