我需要使用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();
}
}
upload.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!";
}
?>
答案 0 :(得分:0)
<?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++;