上传任何文件到服务器

本例是tcp传输的,还有一个是http传输文件的,github地址如下
https://github.com/liang1075963999/http-chuanwenjian
博客地址如下
http://m.blog.csdn.net/ZJi_Hua/article/details/12587677

本例涉及到的知识点如下

1:在android中打开文件管理器的方法
2:对流和字节之间转换的总结,四个字(流读字阴,蝎字流出)
3:uri转换为绝对路径的方式

在客户端,代码如下:

public class WenJian extends Activity {
    private Button shangChuan;
    private Socket socket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wenjian);
        quanXianShenQing();
        //Log.i("xinxi", "onCreate: "+ Environment.getExternalStorageDirectory());
        shangChuan= (Button) findViewById(R.id.shangchuan);
        shangChuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //chuanShuJu(Environment.getExternalStorageDirectory()+"/1.mp3");
                Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//在setType中可以选择不同的文件类型,如video/*,audio/*,file/*等.
                intent.addCategory(intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);

            }
        });
    }

    private void quanXianShenQing() {
        if(ContextCompat.checkSelfPermission(WenJian.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(WenJian.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1){
            //Log.i("xinxi",data.getData().toString());
           /* luJingZhuanHuan(data.getData(),getContentResolver());
            Log.i("xinxi",luJingZhuanHuan(data.getData(),getContentResolver()));*/
            Log.i("xinxi",getFileAbsolutePath(WenJian.this,data.getData()));
            chuanShuJu(getFileAbsolutePath(WenJian.this,data.getData()));
            //chuanShuJu(data.getData().toString());
        }
    }
    private void chuanShuJu(final String s){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        socket=new Socket("192.168.43.24",5554);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    OutputStream outputStream=socket.getOutputStream();
                    byte[] bytes=new byte[1024];
                    File file=new File(s);
                    FileInputStream fileInputStream=new FileInputStream(file);
                    int length;
                    while ((length=fileInputStream.read(bytes))!=-1){
                        outputStream.write(bytes,0,length);
                        outputStream.flush();
                    }
                    outputStream.close();
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private String luJingZhuanHuan(Uri uri, ContentResolver contentResolver){//该方法是只能转换图片的uri
        String filePath;
        String[] fileColumn={MediaStore.MediaColumns.DATA};//
                Cursor cursor=contentResolver.query(uri,fileColumn,null,null,null);
        cursor.moveToFirst();
        int column=cursor.getColumnIndex(fileColumn[0]);
        filePath=cursor.getString(column);
        cursor.close();
        return filePath;
    }
    public static String getFileAbsolutePath(Activity context, Uri fileUri) {
        if (context == null || fileUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, fileUri)) {
            if (isExternalStorageDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(fileUri)) {
                String id = DocumentsContract.getDocumentId(fileUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[] { split[1] };
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(fileUri))
                return fileUri.getLastPathSegment();
            return getDataColumn(context, fileUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
            return fileUri.getPath();
        }
        return null;
    }
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String[] projection = { MediaStore.Images.Media.DATA };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

}

在服务器端:

public class mainactivity {
    private static ServerSocket serverSocket;
    public static void main(String[] args) throws Exception {
        serverSocket = new ServerSocket(5554);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Socket socket;
                while(true){
                    try {
                    if(serverSocket.accept()!=null){
                        socket=serverSocket.accept();
                        new BaoCun(socket).start();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }
                
            }
        }).start();
    }

}
class BaoCun extends Thread{
    private Socket socket;
    public BaoCun(Socket socket) {
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            OutputStream outputStream=socket.getOutputStream();
            InputStream inputStream=socket.getInputStream();
            File file=new File("D:\\CSV", ((int) (Math.random() * 100000)) +".csv");
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            byte[] b1 = new byte[1024];
            int length;
            while((length=inputStream.read(b1))!=-1){
                fileOutputStream.write(b1, 0, length);
            }
            fileOutputStream.close();
            outputStream.close();
            System.out.println("csv文件保存成功");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    
}

你可能感兴趣的:(上传任何文件到服务器)