I am trying to get a document file (PDF) from Android storage, then I want to upload PDF files where I get earlier to the server using Retrofit. I just tried to get and upload it, but the files are not uploaded. It says my files are null. I used Kotlin and here's my code
My Activity
class SignatureUploadFileActivity : AppCompatActivity() {
private val vm: SignatureViewModel by viewModel()
val CREATE_FILE = 1
private lateinit var file: File
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signature_upload_file)
initAction()
initObserver()
}
private fun initAction() {
ll_upload.setOnClickListener {
getpdf()
}
btn_signature_upload.setOnClickListener {
uploadfile()
}
}
private fun uploadfile() {
var body: MultipartBody.Part?
val reqFile = RequestBody.create("application/pdf".toMediaTypeOrNull(), file)
body = MultipartBody.Part.createFormData("profile_picture", file.getName(), reqFile)
vm.signex(body)
}
private fun initObserver() {
vm.signEx.observe(this) {
if (it != null) {
Log.d("Upload File", "Success ${it.message}")
}
}
}
private fun getpdf() {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/pdf"
}
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(intent, CREATE_FILE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
CREATE_FILE -> if (resultCode == Activity.RESULT_OK) {
// Set up an Intent to send back to apps that request a file
if (null != data) {
val uri = data.data!!
file = File(uri.path)
}
}
}
}
}
My API Interface
@Multipart
@POST("/dev/upload")
suspend fun signEx(
@Part file: MultipartBody.Part?
): SignExResponse
My Repository
class SignatureRepository(private val webApi: APIServices) {
suspend fun signatureex(file:MultipartBody.Part):SignExResponse {
lateinit var response: SignExResponse
try {
response = webApi.signEx(file)
Log.d("Signature Mandiri", "Succesfull")
} catch (e: Exception) {
Log.d("Signature Mandiri", "Failed")
}
return response
}
}
Here's my viewmodel
class SignatureViewModel(private val repository: SignatureRepository) : ViewModel() {
private var _signexresponse = MutableLiveData<SignExResponse>()
val signEx: LiveData<SignExResponse>
get() = _signexresponse
fun signex(file:MultipartBody.Part) {
viewModelScope.launch {
try {
val response = repository.signatureex(file)
_signexresponse.value = response
} catch (e: Exception) {
}
}
}
}