Android 高

使用Retrofit 上传图像

2019-03-22  本文已影响5人  穿越平行宇宙

依赖

            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'        //解析图片

            //retrofit基本依赖
            implementation 'com.squareup.retrofit2:retrofit:2.3.0'
            implementation 'io.reactivex.rxjava2:rxjava:2.0.1'    //RxJava
            implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
            implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
            implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

权限

            <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"/>
<?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> 
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;
        }
    }
}
public interface MyServer {

    //http://yun918.cn/study/public/file_upload.php
    String url = "http://yun918.cn/study/public/";

    @Multipart      //文件上传类型头
    @POST("file_upload.php")
    Observable<UpLoadBean> upload(@Part("key")RequestBody key, @Part MultipartBody.Part file);

}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 上传图像
     */
    private Button mBtn;
    private TextView mText;
    private ImageView mImg;
    private File mFile;

    @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) {
            uploadImg();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

    }

    @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) {
            uploadImg();
        } else {
            Toast.makeText(this, "用户取消使用", Toast.LENGTH_SHORT).show();
        }

    }

    private void uploadImg() {

        // 获取文件路劲
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File directory = Environment.getExternalStorageDirectory();
            mFile = new File(directory, "text.jpg");
        }

        // 创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyServer.url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // 获取到指定的集合对象
        MyServer myServer = retrofit.create(MyServer.class);

        // 上传普通参数
        MediaType mediaType = MediaType.parse("application/octet-stream");
        RequestBody requetBody = RequestBody.create(mediaType, "H1808");

        // 上传文件参数
        RequestBody body = RequestBody.create(MediaType.parse("image/jpg"), mFile);
        MultipartBody.Part file = MultipartBody.Part.createFormData("file", this.mFile.getName(), body);

        Observable<UpLoadBean> observable = myServer.upload(requetBody, file);

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpLoadBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UpLoadBean value) {

                        if (value != null) {

                            if (value.getCode() == 200) {
                                mText.setText(value.getRes());

                                Glide.with(MainActivity.this).load(value.getData().getUrl()).into(mImg);

                            } else {
                                mText.setText(value.getRes());

                            }

                        } else {
                            mText.setText("错误");
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
}
上一篇 下一篇

猜你喜欢

热点阅读