繁体   English   中英

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

[英]How to upload a file to server using Java to PHP 5 over HTTP

我一直在研究java / android应用程序,我需要能够从设备上拍照并将其上传到我的ubuntu服务器上,该服务器运行在我的覆盆子pi 2上。

我想在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字节。 任何人都可以帮我解决这个问题吗? 先感谢您!

好的,我发现了我的问题。 我在没有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;

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM