国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android使用OkHttp上傳圖片的實(shí)例代碼

2019-10-22 18:33:09
字體:
供稿:網(wǎng)友

簡介

上傳圖片是一個(gè)APP的常見功能,可以是通過OOS上傳到阿里云,也可以直接上傳到Server后臺(tái),OOS有提供相應(yīng)的SDK,此處忽略。下面通過OkHttp來實(shí)現(xiàn)圖片的上傳

代碼

直接上代碼UploadFileHelper.kt

object UploadFileHelper { //--------ContentType private val MEDIA_OBJECT_STREAM = MediaType.parse("multipart/form-data") //--------上傳延時(shí)時(shí)間 private val WRITE_TIME_OUT:Long = 50 private val mOkHttpClient by lazy { OkHttpClient() } //------基本參數(shù)---------- val version = AppConstant.API_VERSION val platform = AppConstant.API_PLATFORM val methodName = AppConstant.API_UPLOADFILE_METHOD val token = ignoreException("") { UserModel.token() } val userId = ignoreException(0) { UserModel.id() } //------------------------ //不帶參數(shù)同步上傳文件 fun syncUploadFile(actionUrl: String = "",file: File,maxW: Int = 256,maxH: Int = 256):String?{  val uploadFile = optionFileSize(file,maxW,maxH,null)  if(uploadFile!=null){   val response = createNoParamsOkHttpCall(actionUrl,uploadFile).execute()   if(uploadFile.exists())    uploadFile.delete()   return getResponseToPath(response.body()!!.string())  }  return null } //不帶參數(shù)異步上傳文件 fun asyncUploadFile(actionUrl:String = "", file: File,maxW: Int = 256,maxH: Int = 256,      uploadCallBackListener: UploadCallBackListener? = null){  val uploadFile = optionFileSize(file,maxW,maxH,uploadCallBackListener)  if(uploadFile!=null)  createNoParamsOkHttpCall(actionUrl,uploadFile).enqueue(object: Callback{   override fun onFailure(c: Call, e: IOException) {    uploadCallBackListener?.onUploadFailure(e.toString())   }   override fun onResponse(c: Call, response: Response) {    if(uploadFile.exists())    uploadFile.delete()     uploadCallBackListener?.onUploadSuccess(getResponseToPath(response.body()!!.string()))    response.body()!!.close()   }  }) } //帶參數(shù)同步上傳文件 fun syncParamsUploadFile(actionUrl: String= "",file: File,params:HashMap<String,Any>,      maxW: Int = 256,maxH: Int = 256):String?{  val uploadFile = optionFileSize(file,maxW,maxH,null)  if(uploadFile!=null){   params.put("filename",uploadFile)   val response = createParamsOkHttpCall(actionUrl,params,null,false).execute()   if(uploadFile.exists())    uploadFile.delete()   return getResponseToPath(response.body()!!.string())  }  return null } //帶參數(shù)異步上傳文件 fun asyncParamsUploadFile(actionUrl: String= "",file: File,params:HashMap<String,Any>,maxW: Int = 256,maxH: Int = 256,      uploadCallBackListener: UploadCallBackListener? = null, isProgress:Boolean = true){  val uploadFile = optionFileSize(file,maxW,maxH,uploadCallBackListener)  if(uploadFile!=null){   params.put("filename",uploadFile)   createParamsOkHttpCall(actionUrl,params,uploadCallBackListener,isProgress).enqueue(object :Callback{    override fun onFailure(c: Call, e: IOException) {     uploadCallBackListener?.onUploadFailure(e.toString())    }    override fun onResponse(c: Call, response: Response) {      if(uploadFile.exists())      uploadFile.delete()     uploadCallBackListener?.onUploadSuccess(getResponseToPath(response.body()!!.string()))     response.body()!!.close()    }   })  } } //------創(chuàng)建一個(gè)沒有帶參數(shù)的Call fun createNoParamsOkHttpCall(actionUrl: String,file: File):Call{  val requestUrl = "${AppConstant.HOST}/$actionUrl"  val requestBody = RequestBody.create(MEDIA_OBJECT_STREAM,file)  val request = Request.Builder().url(requestUrl).post(requestBody).build()  return mOkHttpClient.newBuilder().writeTimeout(WRITE_TIME_OUT,TimeUnit.SECONDS).build().newCall(request) } //------創(chuàng)建一個(gè)帶參數(shù)的Call fun createParamsOkHttpCall(actionUrl: String,params:Map<String,Any>,        uploadCallBackListener: UploadCallBackListener? = null,        isProgress:Boolean = true):Call{  //-----AppConstant.HOST 上傳圖片的Server的BASE_URL http://xxx.com  val requestUrl = "${AppConstant.HOST}/$actionUrl"  val builder = MultipartBody.Builder()  builder.setType(MultipartBody.FORM)  val newParams = mutableMapOf(    "version" to version,    "platform" to platform,    "methodName" to methodName,    "token" to token,    "user_id" to userId)  newParams.putAll(params)  newParams.forEach( action = {   if(it.value is File){    builder.addFormDataPart(it.key, (it.value as File).name,    if(isProgress) createProgressRequestBody(MEDIA_OBJECT_STREAM!!,(it.value as File),uploadCallBackListener)    else RequestBody.create(null, (it.value as File)))   }else{    builder.addFormDataPart(it.key,it.value.toString())   }  })  val body = builder.build()  val request = Request.Builder().url(requestUrl).post(body).build()  return mOkHttpClient.newBuilder().writeTimeout(WRITE_TIME_OUT,TimeUnit.SECONDS).build().newCall(request) } //創(chuàng)建帶進(jìn)度RequestBody fun createProgressRequestBody(contentType:MediaType,file:File,         uploadCallBackListener: UploadCallBackListener? = null):RequestBody{  return object:RequestBody(){   override fun contentType(): MediaType = contentType   override fun contentLength() = file.length()   override fun writeTo(sink: BufferedSink) {    ignoreException {     val source = Okio.source(file)     val buf = Buffer()     val remaining = contentLength()     var current: Long = 0     var readCount: Long = source.read(buf, 2048)     while (readCount != -1L) {      sink.write(buf, readCount)      current += readCount      uploadCallBackListener?.onUploadProgress(current,remaining)      readCount = source.read(buf, 2048)     }    }   }  } } //根據(jù)圖片大小簡單壓縮 fun optionFileSize(file: File,maxW:Int,maxH:Int,uploadCallBackListener: UploadCallBackListener?):File?{  try {   val uploadFile = File(AppBridge.AppContext().externalCacheDir, file.hashCode().toString())   ImageUtils.resize(file, maxW, maxH, uploadFile)   return uploadFile  } catch (e: Exception) {   uploadCallBackListener?.onUploadFailure("壓縮圖片失敗")   return null  } } //解析Server返回的數(shù)據(jù)獲取圖片路徑, /*  {"code":200,"msg":"上傳成功","data":{"path":""}} */ fun getResponseToPath(response:String):String{  val dataJsonObj = JSONObject(response).get("data") as JSONObject  return dataJsonObj.get("path") as String } //回調(diào)方法 interface UploadCallBackListener{  fun onUploadFailure(error:String)  fun onUploadProgress(currentSize:Long,totalSize:Long)  fun onUploadSuccess(path:String) }}
inline fun <T> ignoreException(def: T, f: () -> T): T { try {  return f() } catch(e: Exception) {  Timber.e(e, "")  return def }}

最后根據(jù)是否要帶參數(shù)、同步或異步調(diào)用其中對(duì)應(yīng)的方法可以了

syncUploadFile(xxx)asyncUploadFile(xxx)syncParamsUploadFile(xxx)asyncParamsUploadFile(xxx)

總結(jié)

首先根據(jù)是否要帶參數(shù)上傳,如果不帶參數(shù)上傳,直接創(chuàng)建RequestBody;如果帶參數(shù)上傳,創(chuàng)建MultipartBody.Builder(),然后把所有參數(shù)addFormDataPart進(jìn)去,其中addFormDataPart方法有個(gè)RequestBody參數(shù)通過是否要監(jiān)聽進(jìn)度創(chuàng)建,如果需要進(jìn)度,需重寫RequestBody的writeTo()方法,如果不監(jiān)聽進(jìn)度,直接創(chuàng)建RequestBody,最后builder.build()得到RequestBody

通過上步驟得到的RequestBody以及上傳圖片的Server路徑,可以配置出一個(gè)Request對(duì)象。

把Request對(duì)象通過.newCall(request)配置在OkHttpClient得到Call對(duì)象

最后Call調(diào)用同步.execute()或者異步.enqueue(callBack),在回調(diào)里面處理返回的數(shù)據(jù)。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到Android開發(fā)頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 共和县| 明水县| 班玛县| 鞍山市| 丰城市| 梅河口市| 台安县| 偏关县| 青铜峡市| 耒阳市| 靖宇县| 谷城县| 永靖县| 柯坪县| 惠水县| 定结县| 泸溪县| 襄城县| 会理县| 萝北县| 新乐市| 永安市| 台北县| 德令哈市| 灵山县| 北辰区| 绥中县| 天峨县| 安龙县| 常州市| 福州市| 安丘市| 鲁山县| 宣武区| 武川县| 双江| 嘉定区| 化德县| 沅陵县| 延安市| 顺义区|