【发布时间】: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