如何使用Java HttpClient 庫和PHP 上傳文件
問題:
A使用HttpClient庫版本4.0 beta2 的Java應用程式嘗試將檔案上傳到執行 PHP 的 Apache 伺服器,但是PHP 腳本無法辨識該檔案。
解決方案:
原始 Java 程式碼使用 FileEntity 物件來傳輸文件,這是不正確的。正確的方法是使用 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 腳本識別。
以上是如何使用Java的HttpClient庫正確上傳檔案到PHP伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!