-3

here is the method i found in internet to upload picture to server. but it crashes. i have no idea why. could somebody help me to solve thus problem? maybe someone did that, and knows more clearer example of uploading photos to php server?

private void doFileUpload() {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String exsistingFileName = "/mnt/sdcard/Pictures/album/test.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://simplify.lt/android/debug";

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

    }

here is the logcat :

05-08 14:51:09.609: E/AndroidRuntime(29477): FATAL EXCEPTION: main
05-08 14:51:09.609: E/AndroidRuntime(29477): Process: com.project.simplify, PID: 29477
05-08 14:51:09.609: E/AndroidRuntime(29477): android.os.NetworkOnMainThreadException
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.project.simplify.StartedReviewsEditActivity.doFileUpload(StartedReviewsEditActivity.java:498)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.project.simplify.StartedReviewsEditActivity.access$4(StartedReviewsEditActivity.java:454)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.project.simplify.StartedReviewsEditActivity$2.onClick(StartedReviewsEditActivity.java:210)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.view.View.performClick(View.java:4438)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.view.View$PerformClick.run(View.java:18422)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.Handler.handleCallback(Handler.java:733)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.Handler.dispatchMessage(Handler.java:95)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.os.Looper.loop(Looper.java:136)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at android.app.ActivityThread.main(ActivityThread.java:5017)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.lang.reflect.Method.invokeNative(Native Method)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at java.lang.reflect.Method.invoke(Method.java:515)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-08 14:51:09.609: E/AndroidRuntime(29477):    at dalvik.system.NativeStart.main(Native Method)
user3416113
  • 61
  • 1
  • 10
  • 1
    Try to call this method from other thread, not from the UI thread. – erakitin May 08 '14 at 12:00
  • what thread? for example – user3416113 May 08 '14 at 12:00
  • this code i took from http://stackoverflow.com/questions/4295417/upload-a-picture-from-android-to-php-server and there is no thread used – user3416113 May 08 '14 at 12:02
  • @user3416113 because at that time, Android still permitted doing network on main thread. Time flies, and Android changed its policy for newer version. Now you have to use `Thread` or `AsyncTask`. Read [here](http://developer.android.com/guide/components/processes-and-threads.html) for more information. – Andrew T. May 08 '14 at 12:05

1 Answers1

1

This is not the right way to perform network operation on main thread it throws an

android.os.NetworkOnMainThreadException

better you create a new thread or else use AsyncTask to achieve so that you can reslove this issue

You can call it like this

  new Thread(new Runnable() {

        @Override
        public void run() {
            doFileUpload();
        }
    }).start();

Note: There should not be any UI operations in method doFileUpload();

Sainath Patwary karnate
  • 3,165
  • 1
  • 16
  • 18