欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

通过文件选择器上传文件

程序员文章站 2022-05-19 15:42:54
...

打开文件选择器

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//无类型限制
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                startActivityForResult(intent, 1);

获取到data后进行解析

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final String requestUrl = "上传地址";
            final Uri uri = data.getData();
            //String type = getContentResolver().getType(uri);
            //String filePath = uri.getPath();

            final File file = new File(getFilePathForN(MainActivity.this, uri));

            if (!file.exists()){
                Toast.makeText(MainActivity.this,"文件不存在",Toast.LENGTH_SHORT).show();
            }
            final String fileName = file.getName();

            new Thread(new Runnable() {
                @Override
                public void run() {


                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody =new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("tempFile",fileName, RequestBody.create(MediaType.parse("multipart/form-data"), file))
                            .build();
                    Request request = new Request.Builder()
                            .header("Authorization", "Client-ID " + UUID.randomUUID())
                            .url(requestUrl)
                            .post(requestBody)
                            .build();
                    try {
                        Response response = client.newCall(request).execute();
                        Log.i("Response", response.toString());
                        if (response.isSuccessful()){
                            //线程里不能用Toast
                            if(Looper.myLooper() == null)
                            {
                                Looper.prepare();
                            }
                            Toast.makeText(MainActivity.this,"上传成功",Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }else {
                            Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_SHORT).show();
                        }
                    } catch (IOException e) {
                        Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }
            }).start();



        }
    }

通过uri获取文件,主要是通过流的方式将文件拷贝到项目目录下再进行读取

小米机型只有两个,DISPLAY_NAME和SIZE,一般通过DISPLAY_NAME=0获取文件名,但是华为机型有50+个参数,_data获取全路径,DISPLAY_NAME获取的值为空,title只有图片能得到全路径其他会没有后缀名

private static String getFilePathForN(Context context, Uri uri) {
        try {
            Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
            int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            String[] type = returnCursor.getColumnNames();
            returnCursor.moveToFirst();

            String name = (returnCursor.getString(nameIndex));




            if (name==null){
                int dataIndex = returnCursor.getColumnIndex("_data");
                String data = returnCursor.getString(dataIndex);
                name = data.substring(data.lastIndexOf("/")+1);
          

            if (name == null){
                throw new NullPointerException("找不到文件");
            }


            File file = new File(context.getCacheDir(), name);
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            returnCursor.close();
            inputStream.close();
            outputStream.close();
            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
相关标签: android