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

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

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-12-09 17:52:10157瀏覽

Why Does My Java HttpClient File Upload to PHP Fail, and How Can I Fix It Using MultipartEntity?

使用Java HttpClient 和PHP 上傳檔案

嘗試使用Java HttpClient 伺服器版本4.0 將檔案上傳到PHP 的Apache 伺服器時出現腳本無法偵測到Java上傳的檔案的問題application.

在給定的 Java 程式碼片段中,錯誤在於使用 FileEntity 來封裝檔案資料。下方修正後的Java 類別使用MultipartEntity,這對於multipart/form-data 上傳至關重要:

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();
    }
}

此修正可確保檔案正確上傳,且PHP 腳本的is_uploaded_file() 方法應傳回true檔案傳輸成功後,如預期。

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

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