美文网首页Android 高
使用Okhttp 上传图像

使用Okhttp 上传图像

作者: 穿越平行宇宙 | 来源:发表于2019-03-22 16:49 被阅读0次
      1. 首先添加依赖和权限

    依赖:

                implementation 'com.android.support:design:27.1.1'  //防止版本错误
                implementation 'com.github.bumptech.glide:glide:3.8.0'      //解析图片(glide图片加载框架)
                implementation 'com.squareup.picasso:picasso:2.3.2'     //解析图片
                implementation 'com.squareup.okhttp3:okhttp:3.10.0'//okhttp3
                implementation 'com.google.code.gson:gson:2.2.4'//gson
    

    权限:

                <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
                <uses-permission android:name="android.permission.INTERNET"/>
    
    • 2.在activity_main.xml文件中写布局
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="上传文件" />
    
        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </LinearLayout> 
    
    • 3.在MainActivity.java 文件中实现效果
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        /**
         * 上传文件
         */
        private Button mBtn;
        private TextView mText;
        private ImageView mImg;
        private File mFile;
        private String url = "http://yun918.cn/study/public/file_upload.php";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
        }
    
        private void initView() {
            mBtn = (Button) findViewById(R.id.btn);
            mBtn.setOnClickListener(this);
            mText = (TextView) findViewById(R.id.text);
            mImg = (ImageView) findViewById(R.id.img);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                default:
                    break;
                case R.id.btn:
                    initData();
                    break;
            }
        }
    
        private void initData() {
    
            // 判断是否有写入数据的权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                uploadFile();
            } else {
                // 获取(请求)权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                        .WRITE_EXTERNAL_STORAGE}, 1);
            }
        }
    
        /**
         * 请求结果
         * @param requestCode
         * @param permissions
         * @param grantResults
         */
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                               @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            
            // 用户是否获取权限
            if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager
                    .PERMISSION_GRANTED) {
                uploadFile();
            } else {
                Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
            }
        }
    
    
    
    
        private void uploadFile() {
    
            // 获取要上传的文件
            mFile = new File("/storage/sdcard0/Pictures/text.jpg");
    
           /* if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File directory = Environment.getExternalStorageDirectory();
                mFile = new File(directory, "text.jpg");
            }*/
    
    
            OkHttpClient client = new OkHttpClient.Builder()
                    .build();
    
            // 设置文件以及文件上传类型封装
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), mFile);
            
            // 文件上传的请求体封装
            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("key", "H1808C")
                    .addFormDataPart("file", mFile.getName(), requestBody)
                    .build();
    
            Request request = new Request.Builder()
                    .url("http://yun918.cn/study/public/file_upload.php")
                    .post(multipartBody)
                    .build();
    
    
            Call call = client.newCall(request);
    
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
    
                    final String result = response.body().string();
    
                    Gson gson = new Gson();
                    final UpLoadBean upLoadBean = gson.fromJson(result, UpLoadBean.class);
    
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
    
                          
                            if (upLoadBean != null) {
    
                                if (upLoadBean.getCode() == 200) {
    
                                    mText.setText(upLoadBean.getRes());
    
                                    Glide.with(MainActivity.this).load(upLoadBean.getData().getUrl()).into(mImg);
    
    
                                } else {
    
                                    mText.setText(upLoadBean.getRes());
    
                                }
    
    
                            } else {
    
                                Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
    
                        }
                    });
    
    
                }
            });
    
    
        }
    }
    
    • 4.bean文件夹下的实体类
    public class UpLoadBean {
    
    
        /**
         * code : 200
         * res : 上传文件成功
         * data : {"url":"http://yun918.cn/study/public/uploadfiles/abc/b.jpg"}
         */
    
        private int code;
        private String res;
        private DataBean data;
    
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getRes() {
            return res;
        }
    
        public void setRes(String res) {
            this.res = res;
        }
    
        public DataBean getData() {
            return data;
        }
    
        public void setData(DataBean data) {
            this.data = data;
        }
    
        public static class DataBean {
            /**
             * url : http://yun918.cn/study/public/uploadfiles/abc/b.jpg
             */
    
            private String url;
    
            public String getUrl() {
                return url;
            }
    
            public void setUrl(String url) {
                this.url = url;
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:使用Okhttp 上传图像

        本文链接:https://www.haomeiwen.com/subject/szfrvqtx.html