我一直在尝试使用Retrofit2将在库中选择的图像发送到服务器,但是它总是给我类似content:/com.android.providers.media.documents/document/image%3A28: open failed:ENOENT (No such file or directory)
的错误。我认为这是因为路径不正确,因为当我检查图库时,路径看起来像这样/storage/emulated/0/Download/images.png
。无论如何,我可以获得正确的路径吗?还是可以使用通过URI
获得的路径来获得图像?谢谢。
选择图片代码:
fun submitFirstKm(view: View) {
Log.d("Path Image", "Path Image : $filepath")
CustomWarningDialog(this, batteryPercentage.toString(), "12312312.123123", edt_first_km.text.toString(), filepath.toString())
.showDialog(Constants.WARNING_DIALOG, "first_km").show()
}
fun startFileChooser(view: View) {
val i = Intent()
i.type = "image/*"
i.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(i, "Choose Picture"), REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
filepath = data.data!!
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, filepath)
img_first_km.setImageBitmap(bitmap)
}
}
上传代码:
private fun submit(){
try {
val file: File = File(uri)
val requestFile: RequestBody = file.asRequestBody("image/*".toMediaTypeOrNull())
val filePhoto : MultipartBody.Part = MultipartBody.Part.createFormData("file",file.name,requestFile)
val firstKm: RequestBody = km.toRequestBody(MultipartBody.FORM)
val coordinates: RequestBody = coordinate.toRequestBody(MultipartBody.FORM)
val batteryPercentage: RequestBody = batteryPercentage.toRequestBody(MultipartBody.FORM)
ApiConfig().getService()
.firstKm(firstKm, coordinates, batteryPercentage, filePhoto)
.enqueue(object : Callback<FirstKmResponse> {
override fun onFailure(call: Call<FirstKmResponse>, t: Throwable) {
Toast.makeText(mContext, "Gagal : ${t.message}", Toast.LENGTH_SHORT).show()
}
override fun onResponse(
call: Call<FirstKmResponse>,
response: Response<FirstKmResponse>
) {
if (response.isSuccessful) {
Toast.makeText(mContext, "Berhasil", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(mContext, "Gagal : ${response.code()}", Toast.LENGTH_SHORT).show()
}
}
})
} catch (e: Exception) {
Log.e("FirstKmException", "Exception $e")
}
}
答案 0 :(得分:0)
///https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
//使用FileUtils通过uri获取实际文件 文件file = FileUtils.getFile(this,fileUri);
//教程 https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server