Android 使用Retrofit +Rxjava 上传多个文件的实例

public class FileRepository extends BaseRepository {

    private final HouseApi houseApi;

    @Inject
    public FileRepository(HouseApi houseApi) {
        this.houseApi = houseApi;
    }

    private Single uploadFile(File file, FileType fileType) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        MultipartBody.Part typePart = MultipartBody.Part.createFormData("type", fileType.value() + "");
        return houseApi.uploadFile(filePart, typePart)
                .map(ApiResponseMapper.create());
    }

    public Single> uploadFilesForList(List filePaths) {
        return Flowable.fromIterable(filePaths)//遍历文件名称
                .map((String pathname) -> new File(pathname))//转换成文件
                .flatMapSingle(file -> FileRepository.this.uploadFile(file, FileType.Normal))//文件上传,并标记是普通文件
                .map(FileResult::getUrl)//将返回的数据变成String -- url
                .toList();//然后使用使用toList 方法将 一个个 的string ->Single>
    }

    public Single> uploadPhotos(List photos) {
        return Observable.fromIterable(photos)
                .map(photo -> photo.getCompressPath() == null ? photo.getPath() : photo.getCompressPath())
                .map(File::new)
                .flatMapSingle(file -> uploadFile(file, FileType.Normal))
                .toList();
    }

    public Single> uploadPhotosForList(List photos) {
        if (photos == null || photos.size() <= 0) {
            return Single.just(new ArrayList<>());
        } else return Observable.fromIterable(photos)
                .map(photo -> photo.getCompressPath() == null ? photo.getPath() : photo.getCompressPath())
                .map(File::new)
                .flatMapSingle(file -> uploadFile(file, FileType.Normal))
                .map(FileResult::getUrl)
                .toList();
    }

}

接口定义

public interface HouseApi {
       @Multipart
    @POST("v1/common/upload")
    Observable> uploadFile(@PartMap Map params,
                                                   @Part MultipartBody.Part file);

    @Multipart
    @POST("v1/common/upload")
    Single> uploadFile(@Part MultipartBody.Part file, @Part MultipartBody.Part typePart);

}

你可能感兴趣的:(RxJava)