我已经搜索了很多,但没有为我的问题找到具体的解决方案。
首先,我正在使用json在php web服务之间与我的Android应用程序进行通信。我的目标是发现为什么变量$uploaded_file
返回空白但文件正常上传到服务器,具有正确的名称和扩展名。如果文件出现在服务器上,$_FILES
数组怎么可能是空白的?
当我通过html表单upfile.html上传文件时,$_FILES
数组不为空。所以,我想我的问题是java发送给php的一些属性,可能是哪一个?请看下面的java方法fileUpload。
upfile.html
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
upload.php的
$uploaded_file = $_FILES["file"]["name"];
if ($_FILES["file"]["error"] > 0)
{
$response["success_image"] = 0;
$response["message_update_image"] = "Error while trying to update image";
die(json_encode($response));
}
else
{
//echo "Name: " . $_FILES["file"]["name"] . "<br>";
if (file_exists("upload/" . $uploaded_file))
{
$response["success_image"] = 0;
$response["message_update_image"] = "Image already exists";
die(json_encode($response));
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $uploaded_file);
$query = "UPDATE user SET image = :image WHERE id = :user";
$query_params = array(
':user' => $_POST['user'],
':image' => $uploaded_file
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success_image"] = 0;
$response["message_update_image"] = "Unable to upload image";
die(json_encode($response));
}
$response["success_image"] = 1;
//$response["message_update_image"] = "Image uploaded";
$response["message_update_image"] = $uploaded_image;
echo json_encode($response);
}
}
?>
将文件发送到php服务器的fileUpload方法。
public int fileUpload(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" +sourceFileUri);
runOnUiThread(new Runnable() {
public void run() {
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(UPLOAD_URL);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=file; filename="
+ fileName + "" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EditProfile.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EditProfile.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EditProfile.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
return serverResponseCode;
} // End else block
}
答案 0 :(得分:0)
我猜您应该将此行更改为:
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ fileName + "\"" + lineEnd)