zl程序教程

您现在的位置是:首页 >  后端

当前栏目

设计模式只看不练可不行,写个上传解耦库练练手(下)

上传设计模式 不行 写个
2023-09-27 14:25:55 时间
⑤ 自定义后拦截器


对响应数据进行处理 如字符串解析显示


class SimpleParsingInterceptor: Interceptor {

 override fun intercept(chain: Interceptor.Chain): Task {

 val task chain.task()

 if(task is ImageTask) {

 task.response?.let {

 var tempContent it.content

 if(tempContent.startsWith( { )) {

 val index: Int tempContent.indexOf( { )

 tempContent tempContent.substring(index)

 try {

 val jsonObject JSONObject(tempContent)

 if (jsonObject.getInt( code ) 200) {

 //解析服务端回传内容

 val mapJson: JSONObject jsonObject.getJSONObject( data )

 var key 

 var image 

 val ite mapJson.keys()

 while (ite.hasNext()) {

 key ite.next()

 image mapJson[key] as String

 task.fileUrl image

 task.fileUrl?.logV()

 } else {

 jsonObject.toString().logV()

 } catch (e: Exception) {

 e.message?.logD()

 return chain.proceed(task)


⑥ 初始化


可以不在App类中初始化 只要保证在upload前init()了就行~


LightUpload.init(LightUploadBuilder()

 // 传入默认配置 可变参数 支持多种类型Task的定制

 .config(LightUploadTask.IMAGE to ImageUploadConfig().apply {

 reqData ReqData(

 uploadUrl http://127.0.0.1:5000/upload ,

 requestMethod POST ,

 headers hashMapOf(

 Charset to utf-8 ,

 connection to keep-alive 

 }, LightUploadTask.VIDEO to VideoUploadConfig()

 .apply {

 reqData ReqData(

 uploadUrl http://127.0.0.1:5000/upload ,

 requestMethod POST ,

 headers hashMapOf(

 Charset to utf-8 ,

 connection to keep-alive 

 // 设置上传请求 同样也是可变参数 支持多种类型定制

 .upload(LightUploadTask.IMAGE to HucUpload())

 // 添加前拦截器

 .addBeforeInterceptor(PictureRotateInterceptor())

 .addBeforeInterceptor(PictureCompressInterceptor())

 .addBeforeInterceptor(VideoCompressInterceptor())

 .addBeforeInterceptor(VideoFrameInterceptor())

 // 添加后拦截器

 .addDoneInterceptors(SimpleParsingInterceptor())


⑦ 调用上传


LightUpload.upload(task CpImageTask().apply {

 filePath path

 needCompress true

 compressPercent (1..100).random()

 callback object : Upload.CallBack {

 override fun onSuccess(task: Task) {

 // 成功回调

 text ${task.response!!.content}\n 

 override fun onFailure(task: Task) {

 // 失败回调

 task.throwable?.message?.let { it1 - shortToast(it1) }

})


0x5、Demo测试

命令行cd到项目的upload-server项目 第一次运行前执行下述命令安装python脚本相关依赖


pip install -r pip install requirements.txt


安装完后 键入下述命令运行脚本


python app.py


然后手机和电脑在同一局域网 配置下代理 输入ipconfig查看本机IP


image


配置下手机 开下charles


image


运行效果如下


image


Logcat也可以看到输出信息


image

Nice~


设计模式:以桥接模式和访问者模式为例,看设计模式在微信小游戏版本迭代中的应用(上) 去年9月份,微信小游戏《羊了个羊》火爆全网,由于同时在线玩家过多,开发商服务器2天之内竟然出现了3次宕机。这在云开发时代是极少出现的,若不是火爆程度大大超出了预期,程序员怎么可能来不及扩容服务器呢