我正在开发具有功能要求上传图像(平移,adhar,支票)的应用程序。
我通过在用户界面中放置图像按钮并单击打开了相机或图库选项,然后用户选择了该选项并执行功能,满足了这一要求。然后图像将作为位图资源存储到图像按钮。
现在我的任务是将jpeg格式的位图图像以多部分格式上传到服务器。
我尝试过此代码
我的活动
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
val inputStream1 = contentResolver.openInputStream(data?.data!!)
bitmap = BitmapFactory.decodeStream(inputStream1)
persistImage(bitmap, "Image")
mUploadPanCardImageButton!!.setImageBitmap(bitmap)
mCheckBoxPanCard?.isChecked = true
mUploadPanCardTextView?.visibility = View.GONE
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
} else if (requestCode == TAKE_PICTURE) {
if (resultCode == Activity.RESULT_OK) {
val extras1 = data?.extras
bitmap = extras1!!.get("data") as Bitmap
persistImage(bitmap, "image of pan in camera")
mUploadPanCardImageButton!!.setImageBitmap(bitmap)
mCheckBoxPanCard?.isChecked = true
mUploadPanCardTextView?.visibility = View.GONE
}else{
}
}
压缩图像:
private fun persistImage(bitmap: Bitmap?, name: String): File {
val filesDir = applicationContext.filesDir
val imageFile = File(filesDir, "$name.jpg")
val os: OutputStream
try {
os = FileOutputStream(imageFile)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, os)
os.flush()
os.close()
} catch (e: Exception) {
// Log.e(javaClass.getSimpleName(), "Error writing bitmap", e)
}
// Toast.makeText(applicationContext,"Image is stored",Toast.LENGTH_LONG).show()
return imageFile
}
在服务器中上传的代码:
try {
val MEDIA_TYPE_JPG = MediaType.parse("image/jpeg")
val requestBody: RequestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("panCardFile",
image,
RequestBody.create(MEDIA_TYPE_JPG,image)
.build();
val request = Request.Builder()
.url("upload url")
.post(requestBody)
.build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("response is failed ", call.request().body().toString())
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
Log.e("response success enterd", response.toString())
if (response.code() == 200) {
val intentUploadDocsPage = Intent(applicationContext, MainActivity::class.java)
startActivity(intentUploadDocsPage)
} else {
}
}
})
// val response = client.newCall(request).execute()
// return JSONObject(response.body()?.string())
} catch (e: UnknownHostException) {
Log.e("unknown", "Error: " + e.localizedMessage)
} catch (e: UnsupportedEncodingException) {
Log.e("unsupported", "Error: " + e.localizedMessage)
} catch (e: Exception) {
Log.e("other", "Other Error: " + e.getLocalizedMessage())
}
我尝试实现此代码,但无法以所需的格式进行转换。我无法确定应放置哪个变量