Uploading a File to an Apache Server with PHP Using Jakarta HttpClient
In this article, we'll explore a common scenario: uploading a file from a Java application to an Apache server running PHP. We'll use Jakarta HttpClient library version 4.0 beta2 to facilitate the file transfer.
Problem:
A developer encountered an issue when trying to upload a file using HttpClient 4.0 beta2. Despite successful communication with the server, the is_uploaded_file method returned false, and the $_FILES variable remained empty, indicating that PHP did not receive the file.
Solution:
The incorrect Java code used previously has been replaced with a corrected 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(); } }
Explanation:
The original error was caused by using a FileEntity for file upload, which was not the appropriate method. The updated code employs a MultipartEntity to create a multipart/form-data HTTP request, which follows the standard protocol for file uploads. By using the correct request format, the server can now successfully receive and process the uploaded file.
The above is the detailed content of How to Successfully Upload a File from Java to an Apache Server Using Jakarta HttpClient?. For more information, please follow other related articles on the PHP Chinese website!