中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Android中利用OkHttp實現一個圖片上傳功能

發布時間:2020-12-08 17:10:32 來源:億速云 閱讀:355 作者:Leah 欄目:移動開發

本篇文章給大家分享的是有關如何在Android中利用OkHttp實現一個圖片上傳功能,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

實現方法如下:

object UploadFileHelper {
 //--------ContentType
 private val MEDIA_OBJECT_STREAM = MediaType.parse("multipart/form-data")
 //--------上傳延時時間
 private val WRITE_TIME_OUT:Long = 50
 private val mOkHttpClient by lazy { OkHttpClient() }
 //------基本參數----------
 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() }
 //------------------------
 //不帶參數同步上傳文件
 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
 }
 //不帶參數異步上傳文件
 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()
   }
  })
 }
 //帶參數同步上傳文件
 fun syncParamsUploadFile(actionUrl: String= "",file: File,params:HashMap<String,Any>,
      maxW: Int = 256,maxH: Int = 256):String&#63;{
  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
 }
 //帶參數異步上傳文件
 fun asyncParamsUploadFile(actionUrl: String= "",file: File,params:HashMap<String,Any>,maxW: Int = 256,maxH: Int = 256,
      uploadCallBackListener: UploadCallBackListener&#63; = 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&#63;.onUploadFailure(e.toString())
    }
    override fun onResponse(c: Call, response: Response) {
      if(uploadFile.exists())
      uploadFile.delete()
     uploadCallBackListener&#63;.onUploadSuccess(getResponseToPath(response.body()!!.string()))
     response.body()!!.close()
    }
   })
  }
 }
 //------創建一個沒有帶參數的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)
 }
 //------創建一個帶參數的Call
 fun createParamsOkHttpCall(actionUrl: String,params:Map<String,Any>,
        uploadCallBackListener: UploadCallBackListener&#63; = 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)

 }

 //創建帶進度RequestBody
 fun createProgressRequestBody(contentType:MediaType,file:File,
         uploadCallBackListener: UploadCallBackListener&#63; = 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&#63;.onUploadProgress(current,remaining)
      readCount = source.read(buf, 2048)
     }

    }
   }
  }
 }
 //根據圖片大小簡單壓縮
 fun optionFileSize(file: File,maxW:Int,maxH:Int,uploadCallBackListener: UploadCallBackListener&#63;):File&#63;{
  try {
   val uploadFile = File(AppBridge.AppContext().externalCacheDir, file.hashCode().toString())
   ImageUtils.resize(file, maxW, maxH, uploadFile)
   return uploadFile
  } catch (e: Exception) {
   uploadCallBackListener&#63;.onUploadFailure("壓縮圖片失敗")
   return null
  }

 }
 //解析Server返回的數據獲取圖片路徑,
 /*
  {"code":200,"msg":"上傳成功","data":{"path":""}}
 */
 fun getResponseToPath(response:String):String{
  val dataJsonObj = JSONObject(response).get("data") as JSONObject
  return dataJsonObj.get("path") as String
 }
 //回調方法
 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
 }
}

最后根據是否要帶參數、同步或異步調用其中對應的方法可以了

syncUploadFile(xxx)

asyncUploadFile(xxx)

syncParamsUploadFile(xxx)

asyncParamsUploadFile(xxx)

總結

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

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

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

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

以上就是如何在Android中利用OkHttp實現一個圖片上傳功能,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

长丰县| 太仆寺旗| 高邑县| 邯郸市| 曲松县| 沁源县| 秦皇岛市| 黄浦区| 乳山市| 乐陵市| 蛟河市| 申扎县| 武陟县| 陈巴尔虎旗| 鄂托克前旗| 盐城市| 溆浦县| 宁德市| 鹤山市| 富源县| 双峰县| 陵川县| 建始县| 巴林右旗| 东源县| 拉萨市| 阜城县| 双鸭山市| 积石山| 石门县| 哈巴河县| 伊川县| 呈贡县| 卢龙县| 和田市| 镇远县| 天峻县| 江北区| 临湘市| 砀山县| 迁西县|