Send File from android mobile to computer or pc using socket programing



Hear is the code which explain you how to send image or data using socket programming from android to pc or pc to android device. after learn this tutorial or demo i think you able to create chat or socket base application to connect pc or android device.

Hear i am create one android project at to send image to pc(server side) and another one is create java class file at pc or server side.


Code at server Side : java file FileServer.java
import java.io.*;
import java.net.*;

public class FileServer {

    public static void main(String[] args) throws IOException {
        int filesize=6022386; // 

        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;

       
        ServerSocket servsock = new ServerSocket(1149);
        while (true) {
          System.out.println("Waiting...");

          Socket sock = servsock.accept();
          System.out.println("Accepted connection hear : " + sock);

       // receive file
            byte [] mybytearray  = new byte [filesize];
            InputStream is = sock.getInputStream();
            FileOutputStream fos = new FileOutputStream("H:\\demo.jpg"); // 
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(mybytearray,0,mybytearray.length);
            current = bytesRead;

            // thanks to dhaval solanki
            do {
               bytesRead =
                  is.read(mybytearray, current, (mybytearray.length-current));
               if(bytesRead >= 0) current += bytesRead;
            } while(bytesRead > -1);

            bos.write(mybytearray, 0 , current);
            bos.flush();
            long end = System.currentTimeMillis();
            System.out.println(end-start);
            bos.close();
          sock.close();
          }
    }

}


Android Side : activity_main.xml

Layout File :
<?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" >
    <EditText
        android:layout_width="match_parent"
        android:id="@+id/ip_edt"
        android:layout_height="60dp" />
    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello" />

    <TextView
        android:id="@+id/tvPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Path: " />

    <Button
        android:id="@+id/bBrowse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Browse" >
    </Button>

    <Button
        android:id="@+id/bSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send" />

    <ImageView
        android:id="@+id/ivPic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ImageView>

</LinearLayout>


Android Class File : MainActivity.java

package com.materialexample;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import in.co.bhadreshtech.materialexample.R;

public class MainActivity extends AppCompatActivity {

    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    private ImageView img;
    private EditText ip_edt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ip_edt = (EditText) findViewById(R.id.ip_edt);
        System.out.println("34");
        img = (ImageView) findViewById(R.id.ivPic);
        System.out.println("36");
        ((Button) findViewById(R.id.bBrowse))
                .setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {
                        System.out.println("40");
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(
                                Intent.createChooser(intent, "Select Picture"),
                                SELECT_PICTURE);
                        System.out.println("47");
                    }
                });
        ;
        System.out.println("51");
        Button send = (Button) findViewById(R.id.bSend);
        final TextView status = (TextView) findViewById(R.id.tvStatus);

        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                final Socket[] sock = new Socket[1];
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            sock[0] = new Socket(ip_edt.getText().toString() + "", 1149);
                            File myFile = new File(selectedImagePath);
                            byte[] mybytearray = new byte[(int) myFile.length()];
                            FileInputStream fis = new FileInputStream(myFile);
                            BufferedInputStream bis = new BufferedInputStream(fis);
                            bis.read(mybytearray, 0, mybytearray.length);
                            OutputStream os = sock[0].getOutputStream();
                            System.out.println("Sending...");
                            os.write(mybytearray, 0, mybytearray.length);
                            os.flush();
                            sock[0].close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println("Connecting...");

                    }
                });
                thread.start();
                // sendfile


            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                TextView path = (TextView) findViewById(R.id.tvPath);
                path.setText("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri);
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}

1 comment:

Anonymous said...

I tried the code but i am not getting the image in my pc. But i am receiving a request from the android app. Please help me .