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

标签 java php http file-upload server

我一直在开发一个 java/android 应用程序,我需要能够从设备拍照并将其上传到我的 ubuntu 服务器上,该服务器在我的 raspberry 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;

    }

关于java - 如何通过 HTTP 使用 Java 到 PHP 5 将文件上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30157637/

相关文章:

java - OpenJDK 7 支持硬 float abi 吗?

java - Spring Boot - 如何将 application.yml 属性定义为 application.properties

java - 这个变量是如何改变的?

php - 为大型公司在 phpmyadmin 中创建大型 Web 应用程序

php - 取消设置/删除构成一对 PHP 的数组元素

java - 在 Eclipse 中查看 http POST 和 GET 数据的最简单/最佳方法?任何插件/工具?

java - hibernate +OSIV。 2 笔交易。可重复读取

php - 单击“保存”按钮时应用程序崩溃

google-chrome - Chrome 63 将 http 更改为 https

http - 在 ColdFusion 2016 上设置用户代理