如何使用Java通过HTTP将文件上传到PHP 5服务器

4
我一直在开发一款Java/Android应用程序,需要能够从设备上拍照并将其上传到我的运行在树莓派2上的Ubuntu服务器。
我想测试php的上传功能,因此我创建了一个简单的html页面,将其转发到我的upload.php文件。

index.html

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

upload.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=         "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been                        uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}
?>

我希望现在通过Java来实现这个,所以我创建了一个Java类来完成这个任务:

ServerManager.java

package servertest;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

/**
 * Created by Pranav on 5/9/2015.
 */
public class ServerManager {

public static void main(String args[]) {
    try {
        new ServerManager().uploadFile("C:\\Users\\Pranav\\Downloads\\ic_server_test.png");
    } catch (IOException ex) {
        Logger.getLogger(ServerManager.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public int uploadFile(String sourceFileUri) throws IOException {
    String userHome = System.getProperty("user.home");

    //Create Client
    HttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost("http://192.168.0.14/upload.php");
    File file = new File("C:\\Users\\Pranav\\Downloads\\ic_server_test.png");
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody contentFile = new FileBody(file);
    mpEntity.addPart("userfile", contentFile);
    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (!(response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")) {
        System.out.println("SUCCESSFUL: Image has been uploaded");
    } else {
        System.err.println("ERROR: Could not upload the image");
    }
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpClient.getConnectionManager().shutdown();

    return 0;
}
}

然而,当我运行这段代码时,总是得到以下响应:
结果
executing request POST http://192.168.0.14/upload.php HTTP/1.1
ERROR: Could not upload the image
HTTP/1.1 200 OK
Sorry, file already exists.Sorry, only JPG, JPEG, PNG & GIF files are         allowed.Sorry, your file was not uploaded.

我怀疑这是由于数据未传输,因为它始终通过大小测试,可能是0字节。有人能帮我解决这个问题吗?提前感谢!

这个之前的帖子可能会有所帮助。 - gokhanakkurt
1个回答

2

好的,我解决了我的问题。我发送了一个没有MultipartEntity的请求,所以php文件无法读取文件。

这是我的新代码

  private static final String UPLOAD_URL = SERVER_IP + "/upload.php";

    public int uploadImageToServer(String fileLocation) throws IOException {

        // the URL where the file will be posted
        String postReceiverUrl = "http://192.168.0.14/upload.php";

        // new HttpClient
        HttpClient httpClient = new DefaultHttpClient();

        // post header
        HttpPost httpPost = new HttpPost(postReceiverUrl);

        //Create File
        File file = new File(fileLocation);
        FileBody fileBody = new FileBody(file);

        //Set up HTTP post
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("fileToUpload", fileBody);

        httpPost.setEntity(reqEntity);

        // execute HTTP post request
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            String responseStr = EntityUtils.toString(resEntity).trim();


            // you can add an if statement here and do other actions based on the response
            System.out.println(responseStr);
            System.out.println(response.getStatusLine());
        }
        return 0;

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接