public class FileRepository extends BaseRepository {
private final HouseApi houseApi;
@Inject
public FileRepository(HouseApi houseApi) {
this.houseApi = houseApi;
}
private Single<FileResult> 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<List<String>> uploadFilesForList(List<String> 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<List<String>>
}
public Single<List<FileResult>> uploadPhotos(List<Photo> 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<List<String>> uploadPhotosForList(List<Photo> 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<ApiResponse<FileResult>> uploadFile(@PartMap Map<String, RequestBody> params,
@Part MultipartBody.Part file);
@Multipart
@POST("v1/common/upload")
Single<ApiResponse<FileResult>> uploadFile(@Part MultipartBody.Part file, @Part MultipartBody.Part typePart);
}