七牛云 上传图片问题
?問題1????? java.net.UnknownServiceException: CLEARTEXT communication to * not permitted by network
在Android O 升 P (8.0升9.0)的時候,會報以下異常
??? java.net.UnknownServiceException: CLEARTEXT communication to * not permitted by network
因為 Android P 是默認禁止訪問http的API的。
解決辦法:
1,使用https
2,暫時先繞過HTTP限制
??? 在res文件夾下創(chuàng)建xml目錄,新建network_security_config.xml文件,名字隨意
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
??? <base-config cleartextTrafficPermitted="true" />
</network-security-config>
?
??? 在AndroidManifest.xml的Application中添加配置引用
<application
?????? ..
??????? android:networkSecurityConfig="@xml/network_security_config"
????? ... >
//data 建議圖片進行文件壓縮上傳?
//token請求java后臺一下獲得七牛云token
//imgKey自行定義的圖片每張圖片不固定格式名?
private fun upLoadData(data: ByteArray, token: String, imgKey: String, success: ((key: String) -> Unit), options: UploadOptions? = null) {Observable.create<String> { emitter ->QiNiuUtil.put(data, imgKey, token, UpCompletionHandler { key, info, _ ->if (info.isOK) {emitter.onNext(key)Log.d("xg", "上傳圖片成功")} else {Log.d("xg", "info上傳圖片失敗${info}")}}, options)}.compose(RxTransformer.io2Main()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({ key -> success.invoke(key) },{ upLoadData(data, token, imgKey, success, options) }) } private fun saveBitmapToFile(file: File): ByteArray? {try {// BitmapFactory options to downsize the imageval o = BitmapFactory.Options()o.inJustDecodeBounds = trueo.inSampleSize = 6// factor of downsizing the imagevar inputStream = FileInputStream(file)//Bitmap selectedBitmap = null;BitmapFactory.decodeStream(inputStream, null, o)inputStream.close()// The new size we want to scale toval REQUIRED_SIZE = 75// Find the correct scale value. It should be the power of 2.var scale = 1while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) {scale *= 2}val o2 = BitmapFactory.Options()o2.inSampleSize = scaleinputStream = FileInputStream(file)val selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2)inputStream.close()return compressAndGenImage(selectedBitmap!!, 50)} catch (e: Exception) {return null}}/*** 壓縮圖片 返回字節(jié)流不保存** @param image* @param maxSize target will be compressed to be smaller than this size.(kb)* @throws IOException*/ @SuppressLint("WrongThread") @Throws(IOException::class) private fun compressAndGenImage(image: Bitmap, maxSize: Int): ByteArray {val os = ByteArrayOutputStream()var options = 100//從不壓縮開始,因為有圖片可能不到壓縮條件image.compress(Bitmap.CompressFormat.JPEG, options, os)//超過MaxKb的話再壓縮while (os.toByteArray().size / 1024 > maxSize) {os.reset()//重新壓縮options -= 10//比例加10image.compress(Bitmap.CompressFormat.JPEG, options, os)}return os.toByteArray() }?這是flutter中插件使用七牛云Android版部分代碼 ? 有疑問請留言
總結
以上是生活随笔為你收集整理的七牛云 上传图片问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 化工图纸中LISP_化工工艺图纸标识代号
- 下一篇: Linux内核——实模式