rxjava上传图片

作者: Ad大成 | 来源:发表于2019-08-09 11:59 被阅读2次

    关于上传图片我们需要搞清楚上传的服务器需要的请求体的参数,再一个就是我们图片的路径 一下是利用MVP模式上传图片的小demo

    Model层 管理数据 存储数据 下载数据

    package com.example.lenovo.upload;
    
    import java.io.File;
    
    import io.reactivex.Observable;
    import io.reactivex.android.schedulers.AndroidSchedulers;
    import io.reactivex.schedulers.Schedulers;
    import okhttp3.MediaType;
    import okhttp3.MultipartBody;
    import okhttp3.RequestBody;
    import okhttp3.ResponseBody;
    import retrofit2.Retrofit;
    import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    /**
     *利用retrofit上传
     */
    
    public class MainModel {
    
        public Observable<ResponseBody> uploadImage(File file){
    
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://yun918.cn/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            MyService myService = retrofit.create(MyService.class);
    
            MediaType mediaType = MediaType.parse("application/octet-stream");
            RequestBody myFileBody=RequestBody.create(mediaType,file);
            MultipartBody.Part fileBody= MultipartBody.Part.createFormData("file",file.getName(),myFileBody);
            MultipartBody.Part key=MultipartBody.Part.createFormData("key","caca");
            Observable<ResponseBody> responseBodyObservable = myService.uploadImage(key, fileBody);
            return responseBodyObservable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
    
        }
    
    }
    

    Presenter 负责桥接M和V层 并对数据进行逻辑处理

    package com.example.lenovo.upload;
    
    import java.io.File;
    
    import io.reactivex.Observable;
    import okhttp3.ResponseBody;
    
    /**
     * Created by lenovo on 2019/8/9.
     */
    
    public class MainPresenter {
    
        public Observable<ResponseBody> uploadImage(File file){
            MainModel mainModel = new MainModel();
            Observable<ResponseBody> observable = mainModel.uploadImage(file);
            return observable;
        }
    
    
    }
    

    View 层 负责获取数据 展示数据 绘制view

    package com.example.lenovo.upload;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.widget.Button;
    import android.widget.ImageView;
    
    import com.bumptech.glide.Glide;
    import com.google.gson.Gson;
    
    import java.io.File;
    import java.io.IOException;
    
    import butterknife.BindView;
    import butterknife.ButterKnife;
    import butterknife.OnClick;
    import io.reactivex.Observable;
    import io.reactivex.Observer;
    import io.reactivex.disposables.Disposable;
    import okhttp3.ResponseBody;
    
    public class MainActivity extends AppCompatActivity {
    
        @BindView(R.id.iv_upload)
        ImageView ivUpload;
        @BindView(R.id.btn_ok)
        Button btnOk;
        private MainPresenter mainPresenter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
            mainPresenter = new MainPresenter();
    
        }
    
        @OnClick(R.id.btn_ok)
        public void onViewClicked() {
            File file = new File("/storage/emulated/0/luobin.jpg");
    
            Observable<ResponseBody> responseBodyObservable = mainPresenter.uploadImage(file);
            responseBodyObservable.subscribe(new Observer<ResponseBody>() {
                @Override
                public void onSubscribe(Disposable d) {
                    Log.i("tag", "onSubscribe: ");
                }
    
                @Override
                public void onNext(ResponseBody responseBody) {
                    try {
                        String string = responseBody.string();
                        Gson gson = new Gson();
                        HttpBean httpBean = gson.fromJson(string, HttpBean.class);
                        String url = httpBean.getData().getUrl();
                        Glide.with(MainActivity.this).load(url).into(ivUpload);
    
                        Log.i("tag", "onNext: "+ string);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                @Override
                public void onError(Throwable e) {
                    Log.i("tag", "onError: "+e.getMessage());
                }
    
                @Override
                public void onComplete() {
    
                }
            });
    
    
        }
    }
    

    retrofit服务设置

    package com.example.lenovo.upload;
    
    import io.reactivex.Observable;
    import okhttp3.MultipartBody;
    import okhttp3.ResponseBody;
    import retrofit2.http.Multipart;
    import retrofit2.http.POST;
    import retrofit2.http.Part;
    
    /**
     * Created by lenovo on 2019/8/9.
     */
    
    public interface MyService {
    
        @Multipart
        @POST("study/public/file_upload.php")
        Observable<ResponseBody> uploadImage(@Part MultipartBody.Part key,@Part MultipartBody.Part file);
    
    }
    

    这里需要注意的是mimeType有一个application/octet-stream可以适配各种类型 有些服务器要必须配置这个type才能请求

    相关文章

      网友评论

        本文标题:rxjava上传图片

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