Send image file using java HTTP POST connections

http post multipart file upload in java
send image over http java
httpurlconnection post file and parameters java
android http post request with parameters
upload file via http java
http post upload file java
java post request
how to upload a file using java httpclient

I'm trying to send an image to a website using Java HTTP POST requests.

I'm using the base code used here Upload files from Java client to a HTTP server:

This is my modification:

String urlToConnect = "http://localhost:9000/upload";
File fileToUpload = new File("C:\\Users\\joao\\Pictures\\bla.jpg");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.

URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
    writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
    writer.println("--" + boundary);
    writer.println("Content-Disposition: form-data; name=\"picture\"; filename=\"bla.jpg\"");
    writer.println("Content-Type: image/jpeg");
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload)));
        for (String line; (line = reader.readLine()) != null;) {
    } finally {
        if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
    writer.println("--" + boundary + "--");
} finally {
    if (writer != null) writer.close();

// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

I get a 200 response code in the end, but the image is buggy, as in, random colors, which make me think it's an error in character encoding. I tried using UTF-8 as in the original example, but that just creates a corrupt image.

I am also 100% sure it's not a serverside problem, because I can use rest clients such as Advanced Rest Client/Postman and they can send an image with no problems.

Can you help me pinpoint what's wrong? Thank you.

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:9000/upload");
    File file = new File("C:\\Users\\joao\\Pictures\\bla.jpg"");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);

    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
    if (resEntity != null) {


Use HttpClient to work out this code. Its always better to use stable libraries other than handling from scratch, unless there is something to be handled in custom way.

Http POST in Java (with file upload), You would probably be better off using something like Apache HttpClient, with which you can build up a POST request programatically. HttpClient httpclient  I'm using the Nokia Series 60 emulator and MMAPI to capture and image and send it to a server via HTTP. Can this be done using HTTP POST or is there another way to get the image to a server via HTTP? sending image to server using HTTP connection (Java Micro Edition forum at Coderanch)

Reader/Writer classes are designed to handle text data, while images are binary. You need to interpret your files as binary:

FileChannel         in  = new FileInputStream(fileToUpload).getChannel();
WritableByteChannel out = Channels.newChannel(connection.getOutputStream());

in.transferTo(0, fileToUpload.size(), out)

Of course, you still need to close all opened resources.

sending image to server using HTTP connection (Java Micro Edition , Can this be done using HTTP POST or is there another way to get the image to a the HTTP connection properties look like and how the image bytes are sent The server then saves it a local file with an appropriate extension (according to  This was one of my experiments in Networking Lab. The aim was to write a java program to send a picture (image) from a computer to another via network using UDP protocol and to display it at the receiving end. Simply, this is the java code to make a java application which can send images from one computer to another over a network.

Today I run into the same issue, I wrote a little nodejs server supports just two routes, upload and download images.

Client should be a java class which sends a images payload via HTTP POST multipart/form-data standard to the server.

If you would like to know why HTTP POST multipart/form-data, please check out the answer from Ciro Santilli from this post: What does enctype='multipart/form-data' mean?

Luckily I found this nice and really good example code:

It shows how we can build up the payload of an multipart http body manuelly without any external lib, only little limitation from my perspective is, that it only handle a mulitpart body with one file.

Because I had no HTML page to sniff the generated POST payload, I used python to generate it and sniff it via wireshark.

Python3 code:

import requests
posturl = 'http://<server>:<port>/<path>'
files = {'image' : open('<file>', 'rb')}
r =, files = files)

Just for note: if we define the parameter files from the requests lib with an dict, it generates an mulipart/form-data content.

Wireshark shows everything very clear and finally I ended up with this for sending java:

HttpURLConnection conn =
        (HttpURLConnection) new URL("http://<server>:<port>/<path>")).openConnection();

// some arbitrary text for multitext boundary
// only 7-bit US-ASCII digits max length 70
String boundary_string = "some radom/arbitrary text";

// we want to write out
conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary_string);

// now we write out the multipart to the body
OutputStream conn_out = conn.getOutputStream();
BufferedWriter conn_out_writer = new BufferedWriter(new OutputStreamWriter(conn_out));
// write out multitext body based on w3 standard
conn_out_writer.write("\r\n--" + boundary_string + "\r\n");
conn_out_writer.write("Content-Disposition: form-data; " +
        "name=\"image\"; " +
        "filename=\""+ <File class instance>.getName() +"\"" +

// payload from the file
FileInputStream file_stream = new FileInputStream(<File class instance>);
// write direct to outputstream instance, because we write now bytes and not strings
int read_bytes;
byte[] buffer = new byte[1024];
while((read_bytes = != -1) {
conn_out.write(buffer, 0, read_bytes);
// close multipart body
conn_out_writer.write("\r\n--" + boundary_string + "--\r\n");

// close all the streams
// execute and get response code

To get the response from the POST just read the input stream accessed via getInputStream(), code snipped in the link.

How to upload a file via a HTTP multipart request in Java without , This post documents how I can upload a file by sending a HTTP How to upload a file via a HTTP multipart request in Java without using any external Connection: keep-alive Referer: http://localhost/GetPostRequest.php  Since the Android developers recommend to use the HttpURLConnection class, I was wondering if anyone can provide me with a good example on how to send a bitmap "file" (actually an in-memory stream) via POST to an Apache HTTP server. I'm not interested in cookies or authentication or anything complicated, but I just want to have a reliable and

Try that:

private DefaultHttpClient mHttpClient;
Context context;
public String error = "";

//Contrutor para que metodos possam ser usados fora de uma activity
public HTTPconector(Context context) {
    this.context = context;

public HTTPconector() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mHttpClient = new DefaultHttpClient(params);

public void FileClientPost(String txtUrl, File file){
        error = "";
        HttpPost httppost = new HttpPost(txtUrl);
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("Image", new FileBody(file));
        mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
    catch (Exception e)
        Log.e(HTTPconector.class.getName(), e.getLocalizedMessage(), e);
        error = e.getMessage();

//Verifica se a rede esta disponível
public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    return false;

public String Get(String txtUrl){
    try {
        URL url = new URL(txtUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        return readStream(con.getInputStream());

    }  catch (ProtocolException e) {
        return "ERRO: "+e.getMessage();
    } catch (IOException e) {
        return "ERRO: "+e.getMessage();

public String Post(String txtUrl){
    File image;

    try {
        URL url = new URL(txtUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        //con.getOutputStream().write( ("name=" + "aa").getBytes());

        return readStream(con.getInputStream());
    } catch (ProtocolException e) {
        return "ERRO: "+e.getMessage();
    } catch (IOException e) {
        return "ERRO: "+e.getMessage();

//Usado para fazer conexão com a internet
public String conectar(String u){
    String resultServer = "";
    try {
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        resultServer = readStream(con.getInputStream());
    } catch (Exception e) {
        resultServer = "ERRO: "+ e.getMessage();

    Log.i("HTTPMANAGER: ", resultServer);
    return resultServer;

//Lê o resultado da conexão
private String readStream(InputStream in) {
    String serverResult = "";
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {

        serverResult = reader.toString();
    }   catch (IOException e) {
        serverResult = "ERRO: "+ e.getMessage();
    } finally {
        if (reader != null) {
            try {
            } catch (IOException e) {
                serverResult = "ERRO: "+ e.getMessage();
    return  serverResult;

private class PhotoUploadResponseHandler implements ResponseHandler<Object>
    public Object handleResponse(HttpResponse response)throws ClientProtocolException, IOException {

        HttpEntity r_entity = response.getEntity();
        String responseString = EntityUtils.toString(r_entity);
        Log.d("UPLOAD", responseString);
        return null;

HttpURLConnection / Upload POST file using HttpURLConnection , File uploads are sent using multipart/form-data POST requests. new URL(​postTarget); HttpURLConnection connection = (HttpURLConnection) url. as the value of field description ; file is the file to be sent - it's of type A multi-​purpose HttpURLConnection class to handle all types of HTTP 25 9-Patch images. Sending a POST request is easy in vanilla Java. Starting with a URL, we need t convert it to a URLConnection using url.openConnection ();. After that, we need to cast it to a HttpURLConnection, so we can access its setRequestMethod () method to set our method. We finally say that we are going to send data over the connection.

Upload file data | Google Drive API, Note: Users can upload any file type to Drive using the Drive UI and Drive attempts If the request succeeds, the server returns the HTTP 200 OK status code A multipart upload request allows you to send metadata along with the data to upload. send is small enough to upload again, in its entirety, if the connection fails. There was this situation when there was a need for my applet to send some log files (generated by some desktop application) on the remote clients. To keep my applet lean, I chose to implement this file upload function by sending a HTTP multipart request when my applet loads on the remote client's browser. Policies were in place to ensure that my applet was able to read the log files and send

Apache HttpClient - Multipart Upload, Apache HttpClient - Multipart Upload - Using HttpClient, we can perform the multipart upload in HTTP client by uploading a simple text file. Following example demonstrates how to send a multipart request using the File; import addBinaryBody("image", new File("logo.png")); //Building a single entity using the  Java HTTP Request. For our HttpURLConnection example, I am using sample project from Spring MVC Tutorial because it has URLs for GET and POST HTTP methods. Below are the images for this web application, I have deployed it on my localhost tomcat server.

Send image to server java, How to transfer or copy a file between computers using java RMI. ConnectThread is for initializing the connection with server. io Send an HTTP GET request to  With BodyPublishers.ofString()we create a new BodyPublisher. It converts high-level Java objectsinto a flow of byte buffers suitable for sending as a request body. HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println(response.body());

  • Think you should add the parameter Content-Transfer-Encoding: binary, since the uploading should be handled in binary form.
  • Maybe problem was because you are using BufferedReader.readLine() to get image?? You of course find image "buggy" because you need to use just, 0, bytes.length) and then outputStream.write(bytes) where outputStream is connection.getOutputStream();
  • i've got this error: STATUS LINE:HTTP/1.1 200 OK Stampo il response: ERROR: File not moved correctlyArray ( [usr_img] => Array ( [name] => FotoProfilo.png [type] => image/jpeg [tmp_name] => /tmp/phpp170qS [error] => 0 [size] => 5327 ) )
  • Note for this to work in build using something like maven you need both httpclient and httpmime dependencies.
  • You probably mean WritableByteChannel, without the extra 'e'. java.nio.channels.WritableByteChannel
  • if the type of fileToUpload is, then why it is causing error on size().
  • if fileToUpload is a, then, it should be length() instead of size().. correct me if I am wrong..