1

I am trying to upload file to a php server from my android device. There is thread with same question but he is using a different method. My Android side code works fine and shows no error message but server is not receiving any file. here is my sample code, I found it online.

import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;

public class uploadfile extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    doFileUpload();
}

private void doFileUpload(){
HttpURLConnection conn =    null;
DataOutputStream dos = null;
DataInputStream inStream = null;    
String exsistingFileName = "/sdcard/def.jpg";

// Is this the place are you doing something wrong.
String lineEnd = "rn";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.168.1.6/index.php";

try
    {
        //------------------ CLIENT REQUEST 
        Log.e("MediaPlayer","Inside second Method");
        FileInputStream fileInputStream = new FileInputStream(new    File(exsistingFileName) );

                                        // open a URL connection to the Servlet
                                        URL url = new URL(urlString);

                                        // Open a HTTP connection to the URL
                                        conn = (HttpURLConnection) url.openConnection();

                                        // Allow Inputs
                                        conn.setDoInput(true);

                                        // Allow Outputs
                                        conn.setDoOutput(true);

                                        // Don't use a cached copy.
                                        conn.setUseCaches(false);

                                        // Use a post method.
                                        conn.setRequestMethod("POST");
                                        conn.setRequestProperty("Connection", "Keep-Alive");
                                        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                                        dos = new DataOutputStream( conn.getOutputStream() );
                                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                                        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                                                            + exsistingFileName + "\"" + lineEnd);
                                        dos.writeBytes(lineEnd);
                                        Log.e("MediaPlayer","Headers are written");

                                        // 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);

                                        // close streams
                                        Log.e("MediaPlayer","File is written");
                                        fileInputStream.close();
                                        dos.flush();
                                        dos.close();

                    }

      catch (MalformedURLException ex)

     {

           Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);

      }



      catch (IOException ioe)

      {

           Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);

      }

      //------------------ read the SERVER RESPONSE
      try {
            inStream = new DataInputStream ( conn.getInputStream() );
            String str;

            while (( str = inStream.readLine()) != null)
            {
                 Log.e("MediaPlayer","Server Response"+str);
            }

            inStream.close();
      }

      catch (IOException ioex){
           Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
      }

    }
    }

and my php server side code is as follows

<?php

 $target_path = "uploads/";

 $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

 if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
 } 

 else{
      echo "There was an error uploading the file, please try again!";
   }
   ?>

Apache is running. When i run server, this error msg appears There was an error uploading the file, please try again!. I have checked the log data in eclipse and what i think is the socket problem but i am not sure. Please help if anyone knows the solution.

11-28 05:37:55.310: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
symcbean
  • 47,736
  • 6
  • 59
  • 94
SilentCoder
  • 271
  • 3
  • 7
  • 16
  • Changed tags - this doesn't appear to be anything to do with PHP - you should be able to check this with a simple test page using a conventional browser – symcbean Dec 03 '10 at 11:08
  • But i think this is a php question as the server code is in php. – SilentCoder Dec 03 '10 at 11:50
  • I tried this code and from what I can tell no file is getting sent in the POST request. I tested using var_dump($_FILES); – Richard Jan 02 '11 at 19:49
  • @SilentCoder , What did you have to do ? – Shrayas Jan 05 '12 at 14:53
  • @SilentCoder I am getting an error "Failed to open stream, No such files or directory on line ---if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) – asloob Jan 08 '13 at 06:28
  • here is a useful [link](http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/). Try it. It will help you. – user609239 Jun 21 '11 at 05:15

2 Answers2

2

It seems that the server is not responding to the client. Try uploading using an ftp connection through the Android application, if that works then check your Apache configuration on accepting connections and the writable directories. When I had a similar problem it turned out that my directory gave no write privileges.

Is the error from Java or from Apache?

George Violaris
  • 315
  • 1
  • 10
  • im tyring to connect but ftp clien failed to connect with the server. I am having confusion how to run server. do i need to run apache and open server url in browser? or do i need to do something else? the error msg is in eclipse log. – SilentCoder Nov 29 '10 at 00:08
  • If you are trying to FTP the data then Apache has nothing to do with it, you need to have an FTP server running. In which case you wouldn't need the PHP file to "catch" what is being uploaded. On the other hand if you are trying to upload using PHP then you should use a "_POST" to pass from your Java to your PHP the filename. The code that you gave us is on the right track however it seems to not know the filename to upload. Hope this helps. – George Violaris Nov 30 '10 at 11:03
  • But what could be the problem that it doesnt know the filename to upload. I am getting a msg "File is written" when i upload file from android code provided above. But at server side i am getting error msg "There was an error uploading the file, please try again!". – SilentCoder Dec 01 '10 at 16:01
  • This probably means that your directories are not writeable. You should chmod your directories to allow writing – George Violaris Dec 01 '10 at 16:16
  • okey ... thanks alot for your reply. Let me try again with another directory. – SilentCoder Dec 01 '10 at 16:18
  • hello george! I have tried to change directory but still same problem and same error :( – SilentCoder Dec 01 '10 at 17:06
  • I wasn't saying to change the directory, you can use the same directory but chmod the write privileges in that directory. Google chmod. – George Violaris Dec 01 '10 at 17:59
  • Thanks for your reply. Now i have changed the mod but getting error from server. There was an error uploading the file, please try again! i think there is some port problem, have a look at last line of my question. – SilentCoder Dec 01 '10 at 20:18
  • i have solved the problem. The problem was that i had few pictures in my emulator sdcard but they were old or may be inaccessible. I have uploaded a new picture in SDCARD and now i am able to upload on server. – SilentCoder Dec 04 '10 at 05:00
1

Change your code in the following way for the correct escape sequences:

Replace

String lineEnd = "rn";

with

String lineEnd = "\r\n";
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
sp3tsnaz
  • 11
  • 1