Wednesday 9 September 2015

Upload Large video file from android device using PHP.

           
              Sharing files has always been one of Android's greatest strengths. A system of "share intents" allow apps to freely exchange data with each other, making it possible to take a picture with your favorite camera app, then send it over to your choice of photo-sharing apps, for instance.

              Even with a wide variety of cloud-based services that are easily accessible through Android's Share functionality, sending actual video files to your friends is still generally a convoluted process.


              Many cloud services have restrictive file size limits, and videos are among the biggest files out there.Without that hurdle in the way, the act of sharing an large file is still an issue.

Now i am describing the android code how to upload the large video file

make one new function

private String uploadVideo(String videoPath) throws ParseException, IOException();


private String uploadVideo(String videoPath) throws ParseException, IOException {
       HttpClient httpclient = new DefaultHttpClient();
                                             httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      
        //hear mansion the URL of your PHP service
        HttpPost httppost = new HttpPost("https://xyx.com/uploadmedia.php");
      
        //FileBody filebodyVideo = new FileBody(new File(videoPath)); //this is also for add file content

        //add file path of your local directory like from sdcard
        ContentBody fileBody=new FileBody(new File(videoPath));
      
        //other paramiter title of the video
        StringBody title = new StringBody( "Title of the video");
        //any description you want to add
        StringBody description = new StringBody("This is a video of the agent");

        //for the progress that how much video had been uploaded
        AndroidMultiPartEntity reqEntity = new AndroidMultiPartEntity(
                new ProgressListener() {

                    @Override
                    public void transferred(long num) {
                        publishProgress((int) ((num / (float) totalSize) * 100));
                    }
                });

        // add all part in to AndroidMultiPartEntity
        reqEntity.addPart("videoFile", fileBody);
        reqEntity.addPart("title", title);
        reqEntity.addPart("description", description);
        
        //set AndroidMultiPartEntity to HttpPost
        httppost.setEntity(reqEntity);
      
        //get total size of the part data. so we can calculate the uploading progress
        totalSize = reqEntity.getContentLength();

        // DEBUG
        System.out.println( "executing request " + httppost.getRequestLine( ) );
       
        //execut the request
        HttpResponse response = httpclient.execute( httppost );
        HttpEntity resEntity = response.getEntity( );
      
        // DEBUG
        System.out.println( response.getStatusLine( ) );
        if (resEntity != null) {
            System.out.println( EntityUtils.toString( resEntity ) );
        } // end if

        if (resEntity != null) {
            resEntity.consumeContent( );
        } // end if

        httpclient.getConnectionManager( ).shutdown( );
      
        return convertStreamToString(resEntity.getContent());
    } // end of uploadVideo( )

call this method in to asyc task



public class UploadLargeFileAsync extends AsyncTask<Void, Integer, String>{
    private long totalSize=0;
   
    private String mLocalSDCardFilePath;
   
    private ProgressDialog progressDialog;
   
    public UploadLargeFileAsync(Context context,String localSDCardfilePath) {
        mLocalSDCardFilePath=localSDCardfilePath;
       
        progressDialog=new ProgressDialog(context);
        progressDialog.show();
        progressDialog.setCancelable(false);
       
    }
   
    @Override
    protected String doInBackground(Void... params) {
       
        try {
            return uploadVideo(mLocalSDCardFilePath);
        } catch (Exception e) {
            return "";
        }
       
    }
   
   
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        System.out.println("Uploading  "+values[0]+"%");
        progressDialog.setMessage("Uploading  "+values[0]+"%");
    }

   
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog.cancel();
    }


public String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(    new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {
            return "";
        }
    }

}




make a few code on php side in file http://xyz.com/uploadmedia.php

header('Content-type: multipart/form-data');
    echo "<pre>";
    print_r($_REQUEST);
    echo "hiiiii";
    var_dump($_FILE);
    echo $fileName = $_FILES['videoFile']['name']."<br>";
    echo $fileTempName = $_FILES['videoFile']['tmp_name']."<br>";
    echo $fileType = $_FILES['videoFile']['type']."<br>";
    echo $fileSize = $_FILES['videoFile']['size']."<br>";
    echo $fileError = $_FILES['videoFile']['error']."<br>";
    if(is_uploaded_file($_FILES['videoFile']['tmp_name'])) {
       
        $dest=  $_FILES['videoFile'] ['name'];
        move_uploaded_file ($_FILES['videoFile'] ['tmp_name'], "uploads/$dest);
    }
    else
    {
        echo "no file found";
    }


No comments:

Post a Comment