How to upload a file using Java HttpClient library working with PHP
Ok, the Java code I used was wrong, here comes the right Java class:
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();
}
}
note using MultipartEntity.
File upload using apache's httpclient library not working
I dug into the PHP source code, and apparently a filename
is required on the Content-Disposition
line. Therefore, adding the following code, from this answer, in the client solves the problem.
FormBodyPart customBodyPart = new FormBodyPart("file", body) {
@Override
protected void generateContentDisp(final ContentBody body) {
StringBuilder buffer = new StringBuilder();
buffer.append("form-data; name=\"");
buffer.append(getName());
buffer.append("\"");
buffer.append("; filename=\"-\"");
addField(MIME.CONTENT_DISPOSITION, buffer.toString());
}
};
entity.addPart(customBodyPart);
Upload files from Java client to a HTTP server
You'd normally use java.net.URLConnection
to fire HTTP requests. You'd also normally use multipart/form-data
encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data
request body. The specification is in more detail described in RFC2388.
Here's a kickoff example:
String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.
The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.
See also
- Using java.net.URLConnection to fire and handle HTTP requests
POST File with HttpURLConnection to PHP
Finally I've solved the problem by adding apache http client library instead of HttpUrlConnection.
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
/*if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}*/
CloseableHttpClient httpclient = HttpClients.createDefault();
InputStream responseStream = null ;
String responseString = "" ;
try {
HttpPost httppost = new HttpPost("http://localhost/test/test.php");
FileBody bin = new FileBody(new File("D:/Jeyasithar/Workspace/Java/TestJava/src/test.txt"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
responseStream = resEntity.getContent() ;
if (responseStream != null){
BufferedReader br = new BufferedReader (new InputStreamReader (responseStream)) ;
String responseLine = br.readLine() ;
String tempResponseString = "" ;
while (responseLine != null){
tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator") ;
responseLine = br.readLine() ;
}
br.close() ;
if (tempResponseString.length() > 0){
responseString = tempResponseString ;
System.out.println(responseString);
}
}
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
File upload with postman works but fails with Apache HttpClient
I had to remove this line
request.setHeader("Content-type", "multipart/form-data");
to make it work. I dont really know why so if someone can help me out with this and give some explanation I'm up for it. For the moment I'm happy because it works now.
Upload a file using Java Swing coupled with php in the server side
Well you can do that using jakarta HttpClient library
"Upload file HttpClient"
The article has both server side (php) and client side (java) code
you need to specify the folder on the PHP code, it is already doing through the method
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
This function checks to ensure that the file designated by $_FILES['userfile'] ['tmp_name'] is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by $_FILES['userfile'] ['name'].
Related Topics
What Is a Stringindexoutofboundsexception - How to Fix It
How to Launch an Activity from Another Application in Android
Android - Get Real Path of a .Txt File Selected from the File Explorer
How to Discover Memory Usage of My Application in Android
View'S Getwidth() and Getheight() Returns 0
How to Get Url from Firebase Storage Getdownloadurl
Android.Content.Res.Resources$Notfoundexception: String Resource Id #0X0
How to Call a Method After a Delay in Android
What's the Best Way to Share Data Between Activities
How to Call a Soap Web Service on Android
Create a File from a Photo Uri on Android
Broadcast Receiver For Checking Internet Connection in Android App
How to Allow All Network Connection Types Http and Https in Android (9) Pie
Why Doesn't Recyclerview Have Onitemclicklistener()
How to Write Files to External Public Storage in Android So That They Are Visible from Windows