Home >Backend Development >PHP Tutorial >Why is my Java HttpClient file upload to a PHP server failing, and how can I fix it using MultipartEntity?
In an attempt to upload a file from Java to an Apache server utilizing PHP, a Java application was created leveraging the Jakarta HttpClient library version 4.0 beta2. However, the PHP script was failing to recognize the uploaded file, resulting in an empty $_FILES array.
The initial Java code was incorrect, as evident from the modified version below:
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(); } }
The key difference lies in the utilization of MultipartEntity, which enables the proper handling of file uploads.
The PHP script remains unchanged:
<?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); } ?>
By employing MultipartEntity in the Java code, the issue of the PHP script failing to detect the uploaded file was resolved, and the file could be successfully transferred and processed on the server.
The above is the detailed content of Why is my Java HttpClient file upload to a PHP server failing, and how can I fix it using MultipartEntity?. For more information, please follow other related articles on the PHP Chinese website!