0

I am trying to upload a file from the simulator to a php server. While there is nothing wrong in logcat or http error log, I don't see the file where it is supposed to be. The server responds with HTTP_OK. Here is the upload function

public void uploadPic() {
    ThreadPolicy tp = ThreadPolicy.LAX;
    StrictMode.setThreadPolicy(tp);

    Log.e("@@@@@@@@@", "Uploadpic called");
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = "/data/icon.jpg";
    String urlServer = "http://192.168.1.9/savepic2.php";
    //String urlServer = "http://winlab.rutgers.edu/~achanda";
    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=\"file\";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)
    //serverResponseCode = connection.getResponseCode();
    Log.e("@@@@@@@", connection.getResponseMessage());

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

}

Here is the PHP code

    <?php
if ($_FILES["file"]["error"] > 0)
{
        echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file"]["tmp_name"]. "<br />";

        $target_path = "uploads/";

        $target_path = $target_path . basename( $_FILES["file"]["name"]);

        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_path)) {
                echo "The file ".  basename( $_FILES["file"]["name"]).
                        " has been uploaded";
        }
        else{
                echo "There was an error uploading the file, please try again!";
        }
}
?>

What else can go wrong here?

1
  • Does PHP issue any of your echos at all? Commented Oct 30, 2011 at 6:37

1 Answer 1

2

After some testing I believe your problem is ether todo with permissions within the manifest or the file dont exist on the emulator or device...

I got the following code to upload to my test server, I used a toast to output the error & a textview to show the result on success.

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.upload"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidUploadActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

AndroidUploadActivity.class

package com.test.upload;
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;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidUploadActivity extends Activity {
    /** Called when the activity is first created. */
    TextView textView1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView1 = (TextView) findViewById(R.id.textView1);
        try {
            upload();
        } catch (Exception e) {
            Toast toast = Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);  
            toast.show();  
            e.printStackTrace();
        }
    }

    public void upload() throws Exception {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = "/sdcard/DCIM/test.png";
        String urlServer = "http://192.168.2.1/androidupload/index.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

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

            FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
            URL url = new URL(urlServer);

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            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];

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

            String serverResponseMessage = connection.getResponseMessage();

            textView1.setText(serverResponseMessage);

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content"></TextView>
</LinearLayout>

PHP (Note this is very insecure):

<?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!";
}
?>
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, this works fine for me. I guess it was a problem with permissions somewhere. Thanks!
I tried the same coding but am getting Internal server Error.I couldn't found what is the cause, can u pls help me
I am gettin following message : 204 No Content.
For future reference, this method should be done in the background of an AsyncTask. Tips: stackoverflow.com/questions/6053602/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.