0

everyone. I am trying to upload picture files from the phone to the Apache web server on my computer, but without success. Here is my code:

package com.testconnectivity;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;

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

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        String pathToOurFile = "/sdcard/Confused.jpg";
        String urlServer = "http://190.213.29.178/connectiontest1.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;

        try
        {
        FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

        outputStream = new DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

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

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0)
        {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        }
        catch (Exception ex)
        {
        //Exception handling
         Log.d("MainActivity", "Print " + ex.toString());

        }

    }
}

// connectiontest1.php

<?php
$target_path  = "./";
$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!";
}
?>

Could somebody please tell me what's the problem? Do I need a web service or is it some other issue?? Any help would be appreciated very much.

D Brown
  • 460
  • 3
  • 8
  • 22
  • Sorry, tried to upload my php code under the comment connectiontest, but it didn't work though. – D Brown Mar 24 '11 at 19:14
  • What error do you get (in java side)? – MByD Mar 24 '11 at 19:41
  • @MByD - No errors registered by the compiler or the console. Any suggestions on where the problem could be? – D Brown Mar 24 '11 at 20:33
  • you have the catch prase. `catch (Exception ex) { //Exception handling }` pint the exception to screen – MByD Mar 24 '11 at 20:45
  • @MByD -Thanks for responding, MByD, but what exactly do you mean by pint? I know I'm supposed to do some exception handling, but I still can't understand why it would be able send the file I have to the Apache server located on my laptop.(Sorry, but I'm kind of new at this) – D Brown Mar 24 '11 at 20:58
  • @Engprof I misspelled, I meant print. inside the catch block add a line like `Log.d("My app", ex.toString());` it will print a String representing the exception to LogCat. it won't send the file, but it will give us indication **why** it failed to send it. – MByD Mar 24 '11 at 21:03
  • @MByD Thanks for that piece of advice. I did as you suggested and the there seems to be a system error that says it can't dispatch a DDM chunk because no handler was defined. Could you tell me what this means? – D Brown Mar 24 '11 at 22:01
  • @Engprof I don't it's related. Did you see this error in the LogCat window? – MByD Mar 24 '11 at 22:06
  • @MByD Yes I saw it in the LogCat window. – D Brown Mar 24 '11 at 23:26
  • @Engprof please add a logCat log to the question. also, change the debug line to `Log.d("My app", "My print >> " + ex.toString());` so it will be easier to identify. – MByD Mar 24 '11 at 23:29
  • @MByD I tried what you suggested and another error came up. It was an IInputConnectionWrapper error that said : showStatusIcon on inactive Input connection. I'm really not sure as to what that means, so can you shed any light on the matter? – D Brown Mar 25 '11 at 00:04
  • @Engprof add a full log to the question, this way, it will be easier to other to help you as well. – MByD Mar 25 '11 at 00:09
  • @MByD what do you mean when you say "full log" to the question? – D Brown Mar 25 '11 at 00:29
  • @Engprof Different approach - add more prints (using `Log.d()`) to the method, every few lines, and see where it falls. – MByD Mar 25 '11 at 00:33
  • @ MByD Thanks, that sounds like a plan. I'll try that and see how it goes. – D Brown Mar 25 '11 at 00:38

2 Answers2

0

Do you get a android.os.NetworkOnMainThreadException?
You should try using an AsyncTask. That worked for me.
Check this: How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
denCorg
  • 1
  • 1
  • 1
    As general advice, it would be good to explain more about why these things are connected, why using an AsyncTask would solve this problem. Also how to confirm that this is the problem, which side should the original poster be looking on for this error. – EdC Sep 15 '12 at 02:54
0

Below this code:

// Enable POST method connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form data;boundary="+boundary);

add the following line:

connection.setRequestProperty("uploadedfile", pathToOurFile );

DK250
  • 1,064
  • 13
  • 11