Saturday 27 October 2012

WIFI Transfer Multiples File from Android to differ location inside sdcard, Smb Host and Remote Host (WAN)


WIFI Transfer Multiples File from Android to sdcard, Smb Host and Remote Host

-The main purpose I created this tutorial post is to help those who want backup\instant transfer file from android to Smb Host ( PC client in the same network range), Remote Host ( Host far away from your place with differ in static IP address), another location in same internal storage of sdcard. Of cause you can customized to suit your own requirement with easy press one button send to multiple location as you need.

-Don't forget to allow the port 5991 to be opened.(any port is never mind, my using port  5991 at here tutorial).

-Refer to  my attachment contains Server Socket folder, placed it into your eclipse Java Project and export
 it into Runable .Jar file and proceed into .exe file by using Launch4j (google & download it!!). Of cause
 you can use my ServerRun.exe which has convert from ServerRun.jar. This time you can dounble it to run this .exe file and it would be appeared as javaw.exe in background windows.

P.S: The port 5991 is found to be ready open by verify under open port test after running on this .exe file.
       (before it is closed.)

its server coding,

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ServerRun {

/**
* @param args
*/
public static void main(String[] args) throws IOException,EOFException {
// TODO Auto-generated method stub
FileOutputStream fos;
BufferedOutputStream bos;
    OutputStream output;
    DataOutputStream dos;
    int len;
    int smblen; 
    InputStream in;
    boolean flag=true;
    DataInputStream clientData;
    BufferedInputStream clientBuff;
    ServerSocket serverSocket = new ServerSocket(5991);
    Socket clientSocket = null;
    clientSocket = serverSocket.accept();
  
    while (true){
    //while(true && flag==true){
      while(flag==true){  
     
       in = clientSocket.getInputStream(); //used  
       clientData = new DataInputStream(in); //use
       clientBuff = new BufferedInputStream(in); //use 
     
   System.out.println("Starting...");  
      
       int fileSize = clientData.read();
          
       ArrayList<File>files=new ArrayList<File>(fileSize); //store list of filename from client directory
       ArrayList<Integer>sizes = new ArrayList<Integer>(fileSize); //store file size from client
       //Start to accept those filename from server
       for (int count=0;count < fileSize;count ++){
           File ff=new File(clientData.readUTF());
           files.add(ff);
       }
       
       for (int count=0;count < fileSize;count ++){
       
           sizes.add(clientData.readInt());
       }
       
          for (int count =0;count < fileSize ;count ++){  
          
          if (fileSize - count == 1){
          flag =false;
          }
         len=sizes.get(count);
                    
           System.out.println("File Size ="+len);                                                
           output = new FileOutputStream("C:/share/" + files.get(count));
           dos=new DataOutputStream(output);
           bos=new BufferedOutputStream(output);
         
           byte[] buffer = new byte[1024];                            
           
           bos.write(buffer, 0, buffer.length); //This line is important
           
          // while (len > 0 && (smblen = clientData.read(buffer)) > 0) { 
           while (len > 0 && (smblen = clientData.read(buffer, 0, (int) Math.min(buffer.length,len))) != -1) {
            dos.write(buffer, 0, smblen); 
                 len = len - smblen;
                 dos.flush();
               }  
             dos.close();  //It should close to avoid continue deploy by resource under view
          }   
                    
  }
  
          if (flag==false){
             clientSocket = serverSocket.accept();
             flag = true;
          }
      
    } //end of while(true)
       
 } 

}


-For Smb Host side, I've created "C:\share" folder and made it it to be SHARED. So I can transfer my file from android (IP Address : 192.168.1.3) to this Smb Host (192.168.1.2). Simple!!!

-Finally, this is my simple android application code used to be performed like these.

 import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;



public class FileTransferLite extends Activity {
    private Button send;
    private Button sendWan;
    private Socket socket;
private File f,fdst;
private FileInputStream fin,fises;
private static Context context;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_transfer_lite);
        send=(Button)findViewById(R.id.send);
        sendWan=(Button)findViewById(R.id.sendWan);
        FileTransferLite.context = getApplicationContext();
        
    
        send.setOnClickListener(new OnClickListener(){
        
        public void onClick(View view){
       
       
        try {
       
        NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(null, "x", "0465"); // replace with actual values  
       
       
        System.out.println("Connecting...");
       
       
        File fil=new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/");
       
        File[] Files=fil.listFiles();
       
        for (int count=0;count < Files.length;count ++){
        System.out.println(Files[count].getName());
       
        }
       
        ///~~~~~~~~~~~~~~~~~~~~~ sending Multiple Files to sdcard inside~~~///
                    for (int count = 0 ; count < Files.length;count ++){
                   
                    fin=new FileInputStream(Files[count].toString());
                    //String filename= Files[count].getName();
                    FileOutputStream fos= new FileOutputStream(Environment.getExternalStorageDirectory() + "/Storage/" + Files[count].getName() );
                   
                       byte[] buff = new byte[8192];
                int lenf;
               
                 while ((lenf = fin.read(buff)) > 0) {
                     fos.write(buff, 0, lenf);
                     fos.flush();
                 }
                 
                         fos.close();
                         
                         File fs = new File(Environment.getExternalStorageDirectory() + "/Storage/" + Files[count].getName());
                         
                         MediaScannerConnection.scanFile(FileTransferLite.this, new String[]{fs.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
     
      public void onScanCompleted(String path, Uri uri) {
      // TODO Auto-generated method stub
     
      }
      });
                         
                    }
                 
           System.out.println("New files is about created");
           Toast.makeText(getApplicationContext(),"New Files is about created", Toast.LENGTH_SHORT).show(); 
               
          //~~~~sending file  to smb host in the same network
          //byte[] buf = new byte[1024];
         
           for (int count = 0 ; count < Files.length;count ++ ){
           
            fises=new FileInputStream(Files[count].toString());
            SmbFile fss=new SmbFile("smb://192.168.1.2/share/" + Files[count].getName(),authentication);
            SmbFileOutputStream smbout=new SmbFileOutputStream(fss);
           
            byte[] buf = new byte[8192];
                int smblen;
               
                 while ((smblen = fises.read(buf)) > 0) {
                     smbout.write(buf, 0, smblen);
                     smbout.flush();
                   }
             smbout.close();
           }
          
           Toast.makeText(getApplicationContext(),"Transfer file is completed!!", Toast.LENGTH_LONG).show(); 
           //closing FileInputStream
           fin.close();
           fises.close();
               
           //close socket connection
           //socket.close();
                     
        }
        catch(Exception e){
        System.out.println("Error::"+e);
        //System.out.println(e.getMessage());
        //e.printStackTrace();
        //Log.i("******* :( ", "UnknownHostException");
        }
       
        }
         
    });
        
        sendWan.setOnClickListener(new OnClickListener(){
            
        public void onClick(View view){
       
       
        try {
       
        Socket sock = new Socket("219.92.229.225", 5991);  //replace with your remote host static IP address.
           System.out.println("Connecting.........");
               
           File myFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/");
           File[] Files = myFile.listFiles();
            
           OutputStream os = sock.getOutputStream(); 
           DataOutputStream dos = new DataOutputStream(os); 
           
           
           dos.writeInt(Files.length);
           
           for (int count=0;count<Files.length;count ++){
             dos.writeUTF(Files[count].getName());
             
           }
           for (int count=0;count<Files.length;count ++){
             
             int filesize = (int) Files[count].length();
             dos.writeInt(filesize);
           }
           
               for (int count=0;count<Files.length;count ++){
       
                   int filesize = (int) Files[count].length();
           byte [] buffer = new byte [filesize];
               
                  //FileInputStream fis = new FileInputStream(myFile);  
                  FileInputStream fis = new FileInputStream(Files[count].toString());
                  BufferedInputStream bis = new BufferedInputStream(fis);  
           
                  //Sending file name and file size to the server 
                  bis.read(buffer, 0, buffer.length); //This line is important
                     

                  dos.write(buffer, 0, buffer.length);   
                  dos.flush(); 
                  
                  //dos.close();
               }  
               
               //Closing socket  
               //dos.close();
                  sock.close();
               
          Toast.makeText(getApplicationContext(),"Transfer file is completed!!", Toast.LENGTH_LONG).show(); 
              socket.close();
        }
       
        catch(Exception e){
        System.out.println("Error::"+e);
        //System.out.println(e.getMessage());
        //e.printStackTrace();
        //Log.i("******* :( ", "UnknownHostException");
        }
       
        }
       
            
       
    });
        
        
    }
}


-One more important things for communication or even transfer file to SMB host, you are required to have JCIFS libraries which is know as external library that is unsupported in eclipse where you need to download latest jcifs-1.3.17 from http://jcifs.samba.org/src/. Extract it and you will find "jcifs-1.3.17" .jar file.

The way to include this external library:
    -Right-click your android project folder in project explorer, click properties, click on libraries tab,
     click on "Add External JARs button to add "jcifs-1.3.17.jar" file.
   -Don't forget to check this libraries on "ORDER and ADD"

  Now you are able to use below libraries import link.
   
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

-My Project Attachment Download Link = 
http://rapidgator.net/file/52871160/FileTransfer.rar.html

1 comment:

  1. The link is die, can you upload it one more time? i really need this for my assignment.

    ReplyDelete