Cara Memuat Naik Fail dari Java ke Pelayan PHP Menggunakan Perpustakaan HttpClient
Dalam panduan ini, kami akan meneroka cara memuat naik fail daripada aplikasi Java ke pelayan Apache yang menjalankan PHP menggunakan perpustakaan Jakarta HttpClient versi 4.0 beta2.
Kod Java
Kod Java di bawah menunjukkan cara memuat naik fail menggunakan perpustakaan HttpClient:
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.FileEntity; 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 Kod
Kod PHP pada bahagian pelayan bertanggungjawab untuk mengendalikan muat naik fail:
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); }
Menyelesaikan masalah
Jika fail tidak berjaya dimuat naik, pastikan:
Atas ialah kandungan terperinci Bagaimana untuk Memuat naik Fail dari Java ke Pelayan PHP Menggunakan HttpClient?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!