如何使用Retrofit2上传图片?

时间:2017-01-16 22:13:11

标签: android retrofit2 rx-java2

我知道Stack Overflow上有很多问题/答案,但是没有一个能解决我的问题。我查看了所有这些内容,例如How to Upload Image file in Retrofit 2然而无法将其投入使用。

一个大问题是我甚至无法在终端中看到--> END POST,这是我在调用API后得到的结果:

D/SlidingMenuFragment: Picture path: /storage/emulated/0/DCIM/Camera/20170112_141004.jpg
D/SlidingMenuFragment: File name: 20170112_141004.jpg
D/OkHttp: --> POST https://my.website.com/api/video/setAvatar http/1.1
D/OkHttp: Content-Type: multipart/form-data; boundary=4a56042f-41f9-47b5-979a-2218ec3efe02
D/OkHttp: Content-Length: 2208146
V/FA: Activity resumed, time: 9496951465
V/FA: Inactivity, disconnecting from the service
I/dalvikvm: Jit: resizing JitTable from 4096 to 8192

这是我的界面:

public interface NetworkService {

    @Multipart
    @POST("api/video/setAvatar")
    Observable<GeneralResponse> getUploadAvatarAPI(@Part MultipartBody.Part file);
}

这是我的服务类:

public class Service {

    private final NetworkService networkService;

    public Service(NetworkService networkService) {
        this.networkService = networkService;
    }

    public Subscription getUploadAvatarAPI(File file,
                                           final NavigationAPICallback callback) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("avatar", file.getName(), requestBody);

        return networkService.getUploadAvatarAPI(part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<GeneralResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        onNetworkError(callback, e);
                    }

                    @Override
                    public void onNext(GeneralResponse response) {
                        callback.onUploadAvatarResponse(response);
                    }
                });
    }
}

最后这是我的网络模块:

@Module
public class NetworkModule {

    private static final long CONNECTION_TIMEOUT = 60 * 1000; // one minute

    private File cacheFile;

    public NetworkModule(File cacheFile) {
        this.cacheFile = cacheFile;
    }

    @Provides
    @Singleton
    Retrofit provideCall() {
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.API_URL_BASE)
                .client(getHttpClientBuilder())
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    private OkHttpClient getHttpClientBuilder() {

        // Setup Logging interceptor
        HttpLoggingInterceptor mLoggingInterceptor = new HttpLoggingInterceptor();
        mLoggingInterceptor.setLevel(MyApp.DEBUG ? HttpLoggingInterceptor.Level.BODY :
                HttpLoggingInterceptor.Level.NONE);

        // Setup OkHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS) //
                .addInterceptor(mLoggingInterceptor)
                ;

        // Add StethoInterceptor to display server requests/responses in chrome://inspect/#devices
        if (MyApp.DEBUG) {
            builder.addNetworkInterceptor(new StethoInterceptor());
        }

        return builder.build();
    }

    @Provides
    @Singleton
    @SuppressWarnings("unused")
    public NetworkService providesNetworkService(Retrofit retrofit) {
        return retrofit.create(NetworkService.class);
    }

    @Provides
    @Singleton
    @SuppressWarnings("unused")
    public Service providesService(NetworkService networkService) {
        return new Service(networkService);
    }
}

用户可以点击他的头像从图库中更改它。我在片段中的onActivityResult()中获得路径:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn,
                    null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            Timber.d("Picture path: " + picturePath);
            cursor.close();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);

            if (navHeaderView != null) {
//                navHeaderView.setImageBitmap(bitmap);

                File file = new File(picturePath);
                Timber.d("File name: " + file.getName());
                mPresenter.uploadPhoto(file);
            }
        }
    }

依赖关系:

// Network
    compile 'com.google.code.gson:gson:2.6.1'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

    // RxJava & RxAndroid
    compile 'io.reactivex:rxjava:1.1.6'
    compile 'io.reactivex:rxandroid:1.2.1'

0 个答案:

没有答案