首頁 >後端開發 >php教程 >為什麼我的 Java HttpClient 檔案上傳到 PHP 伺服器失敗,如何使用 MultipartEntity 修復它?

為什麼我的 Java HttpClient 檔案上傳到 PHP 伺服器失敗,如何使用 MultipartEntity 修復它?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-12-19 15:44:10525瀏覽

Why is my Java HttpClient file upload to a PHP server failing, and how can I fix it using MultipartEntity?

使用PHP 透過Java 的HttpClient 上傳檔案

在嘗試使用PHP 將檔案從Java 上傳到Apache 伺服器時,利用Jakarta 建立了一個Java 應用程式版本4.0 beta2。然而,PHP 腳本無法識別上傳的文件,導致 $_FILES 數組為空。

Java 實作

最初的Java 程式碼不正確,從下面的修改版本可以看出:

import java.io.File;
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;

public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

主要區別在於MultipartEntity 的利用,它可以正確處理檔案

PHP 腳本

PHP腳本保持不變:

<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
  echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
  move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
  echo "Possible file upload attack: ";
  echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
  print_r($_FILES);
}
?>

結論

透過在Java 程式碼中使用MultipartEntity,問題PHP腳本無法偵測上傳檔案的問題已解決,檔案可以成功傳輸並在伺服器上處理。

以上是為什麼我的 Java HttpClient 檔案上傳到 PHP 伺服器失敗,如何使用 MultipartEntity 修復它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn