Skip to content
Advertisement

Uploading an image to server from android using HTTP POST request

I want to upload an image from my android app to a server. I don’t know where the problem is exactly in the code i’m using -it’s suppose to work ! -. It’s the first time I ever do this so I have little knowledge about it.

The code doesn’t catch any exceptions, yet it never enters the if statement where the server response is “200”.. and the image is never uploaded.

and could you please answer the following ?

1) what does this property mean ?

conn.setRequestProperty("uploaded_file", "Thumbnail"+user_id); 

2) why is the meaning of this line ? I understand it’ll use the data output stream to write onto the server , but what are the parameters inside ?

dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=Thumbnail"+
                                  user_id+ lineEnd);

===========

public void upload_to_server(File [] sdDirList, int fileIndex) throws IOException
    {
        final ProgressDialog dialog = ProgressDialog.show(SettingsActivity.this, "", "Uploading Image...", true);
        final String upLoadServerUri = "server side php script goes here";


        //***File path ***//
        final String uploadFilePath = sdDirList[fileIndex].getCanonicalPath();
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(SettingsActivity.this, uploadFilePath, 
                        Toast.LENGTH_SHORT).show();
     }
        });


       //***Display the dialog of the upload state***//

        new Thread(new Runnable() 
        {
            //Sending thread
                public void run() 
              {
                    dialog.show();

                    String fileName = uploadFilePath;
                    int serverResponseCode = 0;
                    HttpURLConnection conn = null;
                    DataOutputStream dos = null;  
                    String lineEnd = "rn";
                    String twoHyphens = "--";
                    String boundary = "*****";
                    int bytesRead, bytesAvailable, bufferSize;
                    byte[] buffer;
                    int maxBufferSize = 1 * 1024 * 1024; 
                    File sourceFile = new File(uploadFilePath); 

                    if (!sourceFile.isFile()) 
                    {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(SettingsActivity.this, "File is not valid..", 
                                        Toast.LENGTH_SHORT).show();
                     }
                        });

                         dialog.dismiss(); 
                         return;
                    }

                    else
                    {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(SettingsActivity.this, "Entered else block", 
                                        Toast.LENGTH_SHORT).show();
                     }
                        });

                         try 
                         { 

                               // open a URL connection to the Servlet
                             FileInputStream fileInputStream = new FileInputStream(sourceFile);
                             URL url = new URL(upLoadServerUri);

                             // Open a HTTP  connection to  the URL
                             conn = (HttpURLConnection) url.openConnection(); 
                             conn.setDoInput(true); // Allow Inputs
                             conn.setDoOutput(true); // Allow Outputs
                             conn.setUseCaches(false); // Don't use a Cached Copy
                             conn.setRequestMethod("POST");
                             conn.setRequestProperty("Connection", "Keep-Alive");
                             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                             conn.setRequestProperty("uploaded_file", "Thumbnail"+user_id); 

                             dos = new DataOutputStream(conn.getOutputStream());

                             dos.writeBytes(twoHyphens + boundary + lineEnd); 
                             dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=Thumbnail"+
                                  user_id+ lineEnd);

                             dos.writeBytes(lineEnd);

                             // create a buffer of  maximum size
                             bytesAvailable = fileInputStream.available(); 

                             bufferSize = Math.min(bytesAvailable, maxBufferSize);
                             buffer = new byte[bufferSize];

                             // read file and write it into form...
                             bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                             while (bytesRead > 0) 
                             {

                               dos.write(buffer, 0, bufferSize);
                               bytesAvailable = fileInputStream.available();
                               bufferSize = Math.min(bytesAvailable, maxBufferSize);
                               bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                              }

                          // send multipart form data necesssary after file data...
                             dos.writeBytes(lineEnd);
                             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                             // Responses from the server (code and message)
                             serverResponseCode = conn.getResponseCode();
                             String serverResponseMessage = conn.getResponseMessage();

                             Log.i("uploadFile", "HTTP Response is : "
                                     + serverResponseMessage + ": " + serverResponseCode);

                             runOnUiThread(new Runnable() {
                                 public void run() {
                                     Toast.makeText(SettingsActivity.this, "reached reponses's if", 
                                             Toast.LENGTH_SHORT).show();
                          }
                             });
                             if(serverResponseCode == 200)
                             {

                                 runOnUiThread(new Runnable() {
                                      public void run() 
                                      {


                                          Toast.makeText(SettingsActivity.this, "File Upload Complete.", 
                                                       Toast.LENGTH_SHORT).show();
                                      }
                                  });                
                             }    

                             //close the streams //
                             fileInputStream.close();
                             dos.flush();
                             dos.close();

                             runOnUiThread(new Runnable() {
                                 public void run() {
                                     Toast.makeText(SettingsActivity.this, "End of Try", 
                                             Toast.LENGTH_SHORT).show();
                          }
                             });

                        } 
                         catch (MalformedURLException ex) 
                        {
                             runOnUiThread(new Runnable() {
                                 public void run() {
                                     Toast.makeText(SettingsActivity.this, "in first catch", 
                                                                         Toast.LENGTH_SHORT).show();
                                 }
                             });


                            dialog.dismiss();  
                            ex.printStackTrace();

                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(SettingsActivity.this, "MalformedURLException", 
                                                                        Toast.LENGTH_SHORT).show();
                                }
                            });

                            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  

                        } 
                         catch (Exception e) 
                         {
                             runOnUiThread(new Runnable() {
                                 public void run() {
                                     Toast.makeText(SettingsActivity.this, "in second catch", 
                                                                         Toast.LENGTH_SHORT).show();
                                 }
                             });

                            dialog.dismiss();  
                            e.printStackTrace();

                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(SettingsActivity.this, "Something went wrong..", 
                                            Toast.LENGTH_SHORT).show();
                                }
                            });
                            Log.e("Upload file to server Exception", "Exception : "
                                                             + e.getMessage(), e);  
                        }

                         runOnUiThread(new Runnable() {
                             public void run() {
                                 Toast.makeText(SettingsActivity.this, "end of else", 
                                                                     Toast.LENGTH_SHORT).show();
                             }
                         });
                        dialog.dismiss();       

                     } // End else block 




              }
        }).start();  

    }

============================

PHP SCRIPT :

<?php
  
    $file_path = "uploads/";
     
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

Advertisement

Answer

1)

conn.setRequestProperty("uploaded_file", "Thumbnail"+user_id); 

there are two parameter,

first parameter : its a variable name(must be same as defined in php file) defined in your php file for getting file..

second parameter : its a file you want to upload..

2)

dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=Thumbnail"+ user_id+ lineEnd);

its like query string you are passing to DataOutputStream.. here you are passing file throug variable (which you defined upside) and file name for that file..

here, uploaded_file is a variable name defined in server(php) and

name & filename are field name (don’t change it)..you can change its value as your need

if you want nice tutorial for uploading file visit this link : Multipart HTTP Requests

Thank you…

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement