0

I am trying to upload a mp3 file from my android device(2.3.3) but failing. I have seen lot of similar queries here but could not find any solution for my problem. I am not very good in php

Following is my implementation in a service which I am starting from an Activity

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

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class SendFileService extends IntentService {
private boolean mFileSent = false;

public SendFileService() {
    super("SendFileService");

}

@Override
protected void onHandleIntent(Intent arg0)
{
    if(arg0 != null)
    {
        final String path = arg0.getStringExtra("path");
        if(path != null & path.length() > 0)
        {
            Thread t = new Thread()
            {
                public void run()
                {
                    try
                    {
                        sendFilewithHTTP(path);
                        while(mFileSent == false)
                        {
                            Thread.sleep(1000 * 60 * 10);// 10 minutes
                            sendFilewithHTTP(path);
                        }   

                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
    }
}

@Override
public void onDestroy()
{
    mFileSent = true;
    super.onDestroy();
}

private void sendFilewithHTTP(String filePath)
{
    //Set a global flag to check
    SharedPreferences settings = getSharedPreferences("INFO", MODE_PRIVATE);

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inStream = null;
    if(filePath == null || filePath.length() <3)
    {
        mFileSent = true;
        return;
    }

    String pathToOurFile = filePath;
    String urlServer = "https://www.xxxx.xx/xxx/xxxxxxxx/xxxxxx.php?lang=en&val=" + settings.getString("val", getString(R.string.VAL));
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

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

    FileInputStream fileInputStream = null;

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

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();
        Log.i("Connecting to: ", urlServer);

        // 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();
        Log.i("File sent to: " + filePath, "Code: " + serverResponseCode + " Message: " + serverResponseMessage);

        mFileSent = true;
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        //connection.disconnect();
        }
        catch (Exception ex)
        {
            Log.i("File sent status ", "Connection Failed");
            ex.printStackTrace();
            try
            {
                if(fileInputStream != null)
                    fileInputStream.close();
                if(connection != null)
                    connection.disconnect();
                if(outputStream != null)
                {
                    outputStream.flush();
                    outputStream.close();
                }

            }
            catch(Exception e)
            {

            }
        }

        try {
            inStream = new DataInputStream ( connection.getInputStream() );
            String str;

            while (( str = inStream.readLine()) != null)
            {
                Log.d("Server response: ", str);
            }
            inStream.close();

      }
      catch (IOException ioex){

      }

      if(connection != null)
        connection.disconnect();


}

}

The following permissions are added in the manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

This is my PHP script running at the server:

    //check if we have a language and val
    $lang=$_GET['lang'];
    $val=$_GET['val'];

if ( (!isset($val)) || (!isset($lang)) ) die('false');
if ( ($val="") || ($lang="") ) die('false');


//get the file
$fn="data/mydata-".uniqid()."-". date("YmdHis") . ".mp3";

if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $fn)) 
{
    die('false: There was no file in the post request');
}


//check if it's am MP3
$mp3_mimes = array('audio/mpeg3', 'audio/x-mpeg-3', 'audio/mpeg'); 
if (!in_array(mime_content_type($fn), $mp3_mimes)) {
  echo "false: Content type not MP3";
    unlink($fn);        

} else 
{

    //now let's check the file size:
    if (filesize($fn)<(1024*1024*10))
    {
        //Do Something      
    }
    else echo "false: File size too big";   
} 

?>

I am able to connect to the server & the HTTP server is sending message code =200 and message=OK. However, the php script is not getting any files. The function move_uploaded_file() is returning false & hence I am getting value false in my device. I have tried with variety of file sizes but failing.

However, I was able to upload a mp3 file to the same php script from my desktop browser. I believe this rules out any possibility of ini file mistakes or security settings issues.

Please help me find the solution.

Thanks in advance

1 Answer 1

1

You haven't checked if the upload succeeded:

if ($_FILES['userfile']['error'] !== UPLOAD_ERR_OK) {
   die("Upload failed with error code " . $_FILES['userfile']['error']);
}

The rest of the HTTP process can work perfectly but still have a failed file upload for any number of reasons, so never ever assume the upload succeeded.

The error codes are defined here.

Sign up to request clarification or add additional context in comments.

2 Comments

After adding your suggested message I got the following message in my android apps from the server:
I got the source of your problem from your suggestion. Content-disposition set from android code was not matching with php server script. It should be uploadedfile.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.