通过文件选择器上传文件

打开文件选择器

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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值