Ad

Showing posts with label Upload File. Show all posts
Showing posts with label Upload File. Show all posts

Sunday, November 17, 2013

Android Internal and External storage

  • Android Internal Storage
    •  Internal storage are private to your application and other applications cannot access them (nor can the user).
    •  When the user uninstalls your application, these files are removed.
  •  Android External Storage
    •  External storage such as SD card can also store application data.
    •  There's no security enforced upon files you save to the external storage.
    •  All applications can read and write files placed on the external storage and the user can remove them.
    •  You need Read and Write permission in External Storage
In this example we are going to save data from an EditText to both Internal Storage and External Storage, and then try to get the data back from the respective storage places.

 FileOutputStream :For save Data
 FileInputStream  :For Display data



Layout - activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Storage Demo" />

    <EditText
        android:id="@+id/InputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:gravity="top|left"
        android:inputType="textMultiLine"
        android:lines="5"
        android:minLines="2"
        android:text="Internal and External Storage" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/InternalStorageSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Internal Storage(Save)" />

    <Button
        android:id="@+id/InternalStorageGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Internal Storage(Display)" />

    <Button
        android:id="@+id/ExternalStorageSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="External Storage(Save)" />

    <Button
        android:id="@+id/ExternalStorageGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="External Storage(Displays)" />

    <TextView
        android:id="@+id/responseText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Activity - MainActivity.java

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class MainActivity extends Activity implements OnClickListener {

    private String filename = "StorageFile.txt";
    private String filepath = "FileStorage";
    File myInternalFile;
    File myExternalFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ContextWrapper contextWrapper = new ContextWrapper(
                getApplicationContext());
        File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
        myInternalFile = new File(directory, filename);

        Button saveToInternalStorage = (Button) findViewById(R.id.InternalStorageSave);
        saveToInternalStorage.setOnClickListener(this);

        Button readFromInternalStorage = (Button) findViewById(R.id.InternalStorageGet);
        readFromInternalStorage.setOnClickListener(this);

        Button saveToExternalStorage = (Button) findViewById(R.id.ExternalStorageSave);
        saveToExternalStorage.setOnClickListener(this);

        Button readFromExternalStorage = (Button) findViewById(R.id.ExternalStorageGet);
        readFromExternalStorage.setOnClickListener(this);

        // check if external storage is available and not read only
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            saveToExternalStorage.setEnabled(false);
        } else {
            myExternalFile = new File(getExternalFilesDir(filepath), filename);
        }

    }

    public void onClick(View v) {

        EditText myInputText = (EditText) findViewById(R.id.InputText);
        TextView responseText = (TextView) findViewById(R.id.responseText);
        String myData = "";

        switch (v.getId()) {
        case R.id.InternalStorageSave:
            try {
                FileOutputStream fos = new FileOutputStream(myInternalFile); // save
                fos.write(myInputText.getText().toString().getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText("");
            responseText.setText("Saved to Internal Storage.(StorageFile.txt)");
            break;

        case R.id.InternalStorageGet:
            try {
                FileInputStream fis = new FileInputStream(myInternalFile); // display
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(myData);
            responseText
                    .setText("Data retrieved from Internal Storage.(StorageFile.txt)");

            break;

        case R.id.ExternalStorageSave:
            try {
                FileOutputStream fos = new FileOutputStream(myExternalFile);
                fos.write(myInputText.getText().toString().getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText("");
            responseText.setText("Saved to External Storage.(StorageFile.txt)");
            break;

        case R.id.ExternalStorageGet:
            try {
                FileInputStream fis = new FileInputStream(myExternalFile);
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(myData);
            responseText
                    .setText("Data retrieved from Internal Storage.(StorageFile.txt)");
            break;

        }
    }

    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }

}

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


Thursday, November 1, 2012

Android Upload Video in server

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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/tv"
    />
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="Browse gallery"
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</Button>
<ImageView android:id="@+id/ImageView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</ImageView>
</LinearLayout>


uploadfile.java

public class uploadfile extends Activity {
    TextView tv = null;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv);
        doFileUpload();
    }
   
    private void doFileUpload(){

          HttpURLConnection conn = null;
          DataOutputStream dos = null;
          DataInputStream inStream = null;

       
          String exsistingFileName = "/sdcard/six.3gp";
          // Is this the place are you doing something wrong.

          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary =  "*****";


          int bytesRead, bytesAvailable, bufferSize;

          byte[] buffer;

          int maxBufferSize = 1*1024*1024;
 
          String urlString = "http://192.168.1.5/upload.php";
         
         
         
          try
          {
          
       
          Log.e("MediaPlayer","Inside second Method");

          FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );



           URL url = new URL(urlString);

           conn = (HttpURLConnection) url.openConnection();

           conn.setDoInput(true);

           // Allow Outputs
           conn.setDoOutput(true);

           // Don't use a cached copy.
           conn.setUseCaches(false);

           // Use a post method.
           conn.setRequestMethod("POST");

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

          
           dos = new DataOutputStream( conn.getOutputStream() );

           dos.writeBytes(twoHyphens + boundary + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
           dos.writeBytes(lineEnd);

           Log.e("MediaPlayer","Headers are written");



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



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

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

          

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

           BufferedReader in = new BufferedReader(
                           new InputStreamReader(
                           conn.getInputStream()));
                String inputLine;
               
                while ((inputLine = in.readLine()) != null)
                    tv.append(inputLine);

          
          
          
           // close streams
           Log.e("MediaPlayer","File is written");
           fileInputStream.close();
           dos.flush();
           dos.close();


          }
          catch (MalformedURLException ex)
          {
               Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
          }

          catch (IOException ioe)
          {
               Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
          }


          //------------------ read the SERVER RESPONSE


          try {
                inStream = new DataInputStream ( conn.getInputStream() );
                String str;
              
                while (( str = inStream.readLine()) != null)
                {
                     Log.e("MediaPlayer","Server Response"+str);
                }
                /*while((str = inStream.readLine()) !=null ){
                   
                }*/
                inStream.close();

          }
          catch (IOException ioex){
               Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
          }
         
         

        }
}

AndroidManifest.xml

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

upload.php

<?php

move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./".$_FILES["uploadedfile"]["name"]);

?>