前言:我在完成大作业的时候对这一部分不太懂,后来经过查阅资料,觉得这个可以作为一个模块来使用。故写此文章来帮助自己记忆。

需要上传图片的界面:

AndroidManifest.xml配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.civilizedcampus"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:requestLegacyExternalStorage="true"android:label="@string/app_name"android:largeHeap="true"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.CivilizedCampus"><!-- 必须与后面的Provider中的authorities相同 --><providerandroid:authorities="com.example.civilizedcampus.fileProvider"android:name="androidx.core.content.FileProvider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_path"/></provider><activityandroid:name=".SubmitActivity"android:exported="false" /><activity android:name=".Register" /><activity android:name=".Login" /><activityandroid:name=".MainActivity"android:exported="true"android:launchMode="singleTask"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

file_path配置资源:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android"><external-pathname="mt-image"path="."/>
</paths>

核心代码:

package com.example.civilizedcampusimport android.annotation.SuppressLint
import android.content.ContentUris
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
import org.json.JSONObject
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOExceptionclass SubmitActivity : AppCompatActivity() , View.OnClickListener{private var dialog:MyDialog?=nullprivate val TAKE_PICTURE=0private val CHOOSE_PICTURE=1var imageUrl = ""var imageUri:Uri?=nullval tag = "Tag"private val permissions = arrayOf("Manifest.permission.CAMERA","Manifest.permission.READ_EXTERNAL_STORAGE","Manifest.permission.WRITE_EXTERNAL_STORAGE","Manifest.permission.MANAGE_EXTERNAL_STORAGE")override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_submit)val imageView = this.findViewById<ImageView>(R.id.iv_choose_pictures)imageView.setOnClickListener {RequestPermissions()dialog = MyDialog(this)dialog!!.show()dialog!!.window?.findViewById<TextView>(R.id.camera)?.setOnClickListener(this)dialog!!.window?.findViewById<TextView>(R.id.photo)?.setOnClickListener(this)dialog!!.window?.findViewById<TextView>(R.id.cancel)?.setOnClickListener(this)}}private fun RequestPermissions(){for (p in permissions){if(ContextCompat.checkSelfPermission(this, p)!=PackageManager.PERMISSION_GRANTED){ActivityCompat.requestPermissions(this, permissions,2)}}}override fun onRequestPermissionsResult(requestCode: Int,permissions: Array<out String>,grantResults: IntArray) {super.onRequestPermissionsResult(requestCode, permissions, grantResults)when(requestCode){2->{for(p in grantResults){if (grantResults.isNotEmpty() &&p==PackageManager.PERMISSION_GRANTED){Log.d(tag, "onRequestPermissionsResult: 成功申请到$p")}else{Toast.makeText(this, "${p}未成功申请成功", Toast.LENGTH_SHORT).show()}}}}}override fun onClick(v: View?) {if(v == null) {Log.d("dialog", "null")return}when(v.id){R.id.camera-> {Log.d("dialog", "camera")val outImage = File(externalCacheDir, "outPut_image.jpg")try {if(outImage.exists()){outImage.delete()}outImage.createNewFile()}catch (e:Exception){e.printStackTrace()}if(Build.VERSION.SDK_INT>=24){imageUri = FileProvider.getUriForFile(this,"com.example.civilizedcampus.fileProvider", outImage)}else{imageUri = Uri.fromFile(outImage)}val openCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)startActivityForResult(openCameraIntent, TAKE_PICTURE)dialog?.dismiss()}R.id.photo -> {Log.d("dialog", "photo")val openAlbumIntent = Intent(Intent.ACTION_GET_CONTENT)openAlbumIntent.type="image/*"startActivityForResult(openAlbumIntent, CHOOSE_PICTURE)dialog?.dismiss()}R.id.cancel -> {Log.d("dialog", "cancel")dialog?.dismiss()}}}override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {super.onActivityResult(requestCode, resultCode, data)if(resultCode== RESULT_OK){when(requestCode){CHOOSE_PICTURE ->{if (data!=null){if (Build.VERSION.SDK_INT>=19){handleImageONKitKat(data)}else{handleImageBeforeKitKat(data)}val image=this.findViewById<ImageView>(R.id.iv_choose_pictures)Glide.with(this).load(imageUrl).into(image)}}TAKE_PICTURE ->{try {val bitmap = BitmapFactory.decodeStream(imageUri?.let {contentResolver.openInputStream(it)})Log.d(tag,"take success")imageUrl = uploadImage(saveFile(bitmap))val image=this.findViewById<ImageView>(R.id.iv_choose_pictures)Glide.with(this).load(imageUrl).into(image)Log.d(tag,"imageUrl=$imageUrl")}catch (e:Exception){e.printStackTrace()}}}}}@RequiresApi(api = Build.VERSION_CODES.KITKAT)fun handleImageONKitKat(data:Intent){val uri = data.datavar imagePath:String? = nullLog.d(tag,"uri=$uri")if (uri==null){Log.d(tag,"uri wrong")}else{if(DocumentsContract.isDocumentUri(this,uri)){val docId = DocumentsContract.getDocumentId(uri)Log.d(tag,"docId=$docId")if("com.android.providers.media.documents" == uri.authority){val id = docId.split(":")[1]Log.d(tag,"id=$id")val selection = "${MediaStore.Images.Media._ID}=$id"Log.d(tag,"selection=$selection")imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection)Log.d(tag,"imagePath=$imagePath")}else if("com.android.providers.downloads.documents"==uri.authority){val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),docId.toLong(),)Log.d(tag,"contentUri=$contentUri")imagePath=getImagePath(contentUri,null)}}else if ("content".equals(uri.scheme,true)){imagePath = getImagePath(uri,null)}else if ("file".equals(uri.scheme,true)){imagePath = uri.path}val file = imagePath?.let { saveFile(it) }if (file!=null){imageUrl=uploadImage(file)Log.d(tag,"imageUrl=$imageUrl")}}}fun handleImageBeforeKitKat(data:Intent){val uri = data.dataval file = uri?.let { getImagePath(it,null)?.let { saveFile(it) } }if (file!=null){imageUrl=uploadImage(file)Log.d(tag,"imageUrl=$imageUrl")}}@SuppressLint("Range")private fun getImagePath(uri: Uri, Selection:String?):String?{var path:String? = nullval cursor = contentResolver.query(uri, null, Selection, null,null)if(cursor!=null){if(cursor.moveToFirst()){path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))}cursor.close()}return path}private fun saveFile(imagePath:String):File?{if(imagePath!=null){val bitmap = BitmapFactory.decodeFile(imagePath)val file = File("${Environment.getExternalStorageDirectory().absolutePath}/image.jpg")if (file.exists()){file.delete()}try {val bos = BufferedOutputStream(FileOutputStream(file))bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)bos.flush()bos.close()}catch (e:IOException){e.printStackTrace()}return file}else{return null}}private fun saveFile(bitmap: Bitmap):File{val file = File("${Environment.getExternalStorageDirectory().absolutePath}/image.jpg")if (file.exists()){file.delete()}try {val bos = BufferedOutputStream(FileOutputStream(file))bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)bos.flush()bos.close()}catch (e:IOException){e.printStackTrace()}return file}private fun uploadImage(file: File):String{val client = OkHttpClient()var result=""val url = "your upload url"val image = file.asRequestBody("image/jpg".toMediaTypeOrNull())val requestBody = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.name, image).build()val request = Request.Builder().url(url).post(requestBody).build()client.newCall(request).enqueue(object: Callback{override fun onFailure(call: Call, e: IOException) {Log.d(tag,"网络错误")e.printStackTrace()}override fun onResponse(call: Call, response: Response) {if (response.body!=null){Log.d(tag,"upload success")val jsonObject = JSONObject(response.body!!.string())result = jsonObject.optString("data")}}})Thread.sleep(1000)return result}
}

相关资料:大佬的博客
github仓库地址:传送门

校园随手拍之Android从相册选取图片或拍摄图片并上传(kotlin版)相关推荐

  1. android头像相册/拍照选取,裁剪及上传综合案例

    在android项目中,很多情况下上传头像的需求,像qq,新浪微博,微信,飞信等很多应用都有这样的功能. 之前我写过的两篇文章:andorid下从相册选取/拍照选取一张相片并剪切和android下Bi ...

  2. Android实现拍照选择相册图片上传图片(多图片上传)功能

    安卓多图片上传代码 直接上代码 1.主程序入口XML文件 <?xml version="1.0" encoding="utf-8"?> <ma ...

  3. Android 本地tomcat服务器接收处理手机上传的数据之案例演示

    上一篇:Android 本地tomcat服务器接收处理手机上传的数据之环境搭建     本篇基于上一篇搭建的服务器端环境,具体介绍Android真机上传数据到tomcat服务器的交互过程   场景:A ...

  4. android com.mylhyl,Android 高仿微信朋友圈拍照上传功能

    模仿微信朋友圈发布动态,输入文字支持文字多少高度自增,有一个最小输入框高度,输入文字有限制,不过这些都很easy! 1. photopicker的使用 这是一个支持选择多张图片,点击图片放大,图片之间 ...

  5. android 微信高仿,Android 高仿微信朋友圈拍照上传功能

    模仿微信朋友圈发布动态,输入文字支持文字多少高度自增,有一个最小输入框高度,输入文字有限制,不过这些都很easy! 1. PhotoPicker的使用 这是一个支持选择多张图片,点击图片放大,图片之间 ...

  6. android一键发布,Android apk项目如何一键打包并上传到蒲公英

    Android apk项目如何一键打包并上传到蒲公英 发布时间:2020-07-18 15:13:44 来源:亿速云 阅读:107 作者:小猪 这篇文章主要为大家展示了Android apk项目如何一 ...

  7. Android 通过python实现自动化构建打包上传加固

    Android 通过python实现自动化构建打包上传加固 实现需求: 基于gradle命令,通过python实现多渠道,多环境打包,上传蒲公英,360加固等 经过学习调研完成步骤如下: 一,通过gr ...

  8. android 从相册选取图片在小米手机报错的解决办法

    在跳转到系统相册选取照片的时候,用如下代码跳转: Intent albumIntent = new Intent(Intent.ACTION_PICK, null);/*** 下面这句话,与其它方式写 ...

  9. 调用android的拍照或本地相册选取再实现相片上传服务器,Android调用系统相机、本地相册上传图片(头像上传(裁剪)、多张图片上传)...

    开发中基本上都会有头像上传的功能,有的app还需要多张图片同时上传,下面简单将头像上传以及多张图片上传功能整理一下.图片选择仿照微信选择图片的界面.[参考] 多图片选择器 !!!推荐一个动态权限请求的 ...

最新文章

  1. 美多商城之验证码(图形验证码)
  2. Database之SQLSever:SQLSever基础知识进阶、软件安装注意事项、软件使用经验总结之详细攻略
  3. 明天是你的生日~~~
  4. windows服务器双网卡链路聚合_基于windows server 2012的多网卡链路聚合实验设计与......
  5. vue+node实现中间层同步调用接口
  6. [渝粤教育] 中国地质大学 企业文化建设与管理 复习题
  7. 1089 狼人杀-简单版 (20 分)
  8. python中的常量可以修改吗_深入理解Python变量与常量
  9. MySQL(一):分别基于mysqldump、lvm2、xtrabackup三种方式实现备份恢复
  10. 风好大,我好冷——个人分工理解
  11. 牛顿法为什么比梯度下降法求解需要的迭代次数更少?
  12. 扇贝有道每日一句180904
  13. python下载pyhive包:
  14. 计算机教学模式有待创新,计算机软件教学中教学评价模式的创新与探索
  15. 计算机各部分名称ppt,PowerPoint软件界面各部分名称(PPT2010/2013/2016)
  16. 高级创意,单片机电子DIY制作精华资料汇总
  17. MPChart饼图自定义图例
  18. 托疫情的“福”,和儿子一起过了个暑假
  19. 别让你20多岁的活法,毁掉你30岁后的人生
  20. 三代UHS超高速SD卡

热门文章

  1. ID Tech 5 中Megatexture针对地形的D3D9 基本实现原理
  2. STM32控制16路舵机控制板PCA9685
  3. 战争雷霆steam正在连接服务器,战争雷霆玩steam好还是腾讯
  4. 通达信头肩底形态选股公式,突破波峰发出信号
  5. 中兴交换机,中兴路由器Telnet用户登录,配置
  6. 2020年全球光伏逆变器出货量将达90GW
  7. shell脚本案例(一):常见运维面试题
  8. Win10分屏操作分屏操作快捷键
  9. word不能输入中文的解决办法
  10. 问题:2345这种软件不犯法吗?