1

I have searched all over for a good code for uploading an mp3 or similar file to a php server and have tested over 10 samples but none has been successful so far. Most codes I have checked out are either full of bugs or use outdated libraries.

I would appreciate if anyone has a truly working code sample. Possibly one that uses volley or a similar library. Would appreciate any help or some code that points me in the right direction.

Thanks

1 Answers1

1

You can use loopj Android Asynchronous Http Client lib for uploading file to the php server. download the lib file from given link and put into your project's libs folder and use this code for uploading file.

public void postFile(){
    RequestParams params = new RequestParams();
    params.put("fileTitle","MyFile1");
    params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"

    AsyncHttpClient client = new AsyncHttpClient();

    client.post("http://www.yourweserviceurlhere.com", params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                byte[] responseBody, Throwable error) {
            // TODO Auto-generated method stub

        }                                                                                                                                              
    }); 
}

if you want progress of uploading. then you can use my custom design class. for this also require common io 2.4 lib reference in converting HTTPresponse into string.

public class AsyncLoader {
private String url;
private LoaderCallBackHandler mCallback;
private Context mContext;
private RequestParams params;
private RequestHandle handle;

public interface LoaderCallBackHandler {        
    public void onStartUploading();
    public void uploadComplete(String response);
    public void failedWithError(Throwable error);
    public void progressUpdate(long bytesWritten, long bytesTotal);
    public void onCancle();
    public void onFinish();
}


public AsyncLoader(Context mContext,String url,RequestParams params, LoaderCallBackHandler callback) {
    this.mContext = mContext;
    this.url = url;
    this.params = params;
    this.mCallback = callback;     

}

public void startTransfer() {       
    AsynchConfig.mClient.setTimeout(50000);        
    handle = AsynchConfig.mClient.post(mContext, url, params,handlerInterface);
}    
private ResponseHandlerInterface handlerInterface = new ResponseHandlerInterface() {

    @Override
    public void sendStartMessage() {
        if(mCallback != null) {
            mCallback.onStartUploading();               
        }

    }

    @Override
    public void sendResponseMessage(HttpResponse response) throws IOException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();

            // TODO convert in stream to JSONObject and do whatever you need to

            StringWriter writer = new StringWriter();
            IOUtils.copy(instream, writer, Charset.defaultCharset());
            String theString = writer.toString();

            if(mCallback != null) {
                mCallback.uploadComplete(theString);
            }
        }

    }

    @Override
    public void sendSuccessMessage(int arg0, org.apache.http.Header[] arg1, byte[] arg2) {

    }

    @Override
    public void sendFailureMessage(int arg0, org.apache.http.Header[] arg1,
            byte[] arg2, Throwable error) {
            if(mCallback != null) {
                 mCallback.failedWithError(error);
            }
    }

    @Override
    public void sendFinishMessage() {
        if(mCallback != null) {
            mCallback.onFinish();
        }
    }

    @Override
    public void sendProgressMessage(long bytesWritten, long bytesTotal) {
        if(mCallback != null) {             
            mCallback.progressUpdate(bytesWritten, bytesTotal);
        }

    }

    @Override
    public void setUseSynchronousMode(boolean arg0) {
    }

    @Override
    public void setRequestURI(URI arg0) {
    }

    @Override
    public void setRequestHeaders(org.apache.http.Header[] arg0) {
    }

    @Override
    public URI getRequestURI() {
        return null;
    }
    @Override
    public org.apache.http.Header[] getRequestHeaders() {
        return null;
    }

    @Override
    public void sendCancelMessage() {

        if(mCallback != null) {
            mCallback.onCancle();
            mCallback.onFinish();
        }
    }

    @Override
    public void sendRetryMessage(int retryNo) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean getUseSynchronousMode() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void setUsePoolThread(boolean usePoolThread) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean getUsePoolThread() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onPreProcessResponse(ResponseHandlerInterface instance,
            HttpResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPostProcessResponse(ResponseHandlerInterface instance,
            HttpResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setTag(Object TAG) {
        // TODO Auto-generated method stub

    }

    @Override
    public Object getTag() {
        // TODO Auto-generated method stub
        return null;
    }
};

/**
* Cancel upload by calling this method
*/
public void cancel() throws Exception {
    AsynchConfig.mClient.cancelAllRequests(true);
    handle.cancel(true);

}
}

Asynch config class

public final class AsynchConfig {   
     public static AsyncHttpClient mClient = new AsyncHttpClient();
}

Use

RequestParams params = new RequestParams();
params.put("fileTitle","MyFile1");
params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"

AsyncLoader asyncUploader = new AsyncLoader(this, "URL_HERE", params, callHandler);
asyncUploader.startTransfer();

CallHandler Interface object

LoaderCallBackHandler callHandler = new LoaderCallBackHandler() {

    @Override
    public void uploadComplete(String response) {
        // TODO Auto-generated method stub

    }

    @Override
    public void progressUpdate(long bytesWritten, long bytesTotal) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStartUploading() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCancle() {
        // TODO Auto-generated method stub

    }

    @Override
    public void failedWithError(Throwable error) {
        // TODO Auto-generated method stub

    }
};

PHP service for handling uploaded file

if(isset($_FILES['file']) && isset($_POST['fileTitle']) ) {
include './config.php';

//Randomly genrate file name
$stickerTmp = explode(".", $_FILES["file"]["name"]);
$file = md5(date("l, F d, Y h:i" ,time()) . (microtime())).".".end($stickerTmp);

//geting the temp location of file
$filetemploc=$_FILES['file']['tmp_name']; 

//path for uploading to the specific location
$pathandname="file_store/".$file;

// moving the file to specified path
$resultUpload = move_uploaded_file($filetemploc, $pathandname);

// if file is successfully moved to over specified path then insert the reference into the DB
if($resultUpload == TRUE) {
    //echo "File has been moved from : ". $filetemploc . " to  :".$pathandname;

    $qInsert = "INSERT INTO file_lists values (null,'".$_POST['fileTitle']."','".$file."') ";
    mysql_query($qInsert);
}

}
Bhavesh Rangani
  • 1,490
  • 12
  • 23
  • Thanks. Will try it out asap but will appreciate if you can add the PHP code for receiving the file on the server. – Edwin Okugbo Oct 03 '15 at 08:00
  • Thanks. Was just about to post that it actually worked with my own php code. This is the is best and simplest file upload code I have seen so far. So easy and fast. Thanks again. I havent tried your custom class but the function worked fine. Will also try it for large files and see how it goes. – Edwin Okugbo Oct 03 '15 at 10:42