我正在尝试通过改造将文件上传到服务器。在邮递员中我成功收到了 api 响应。
但是当我在项目中调用 api 时,api 调用失败。
改装方法:
@Multipart
@POST("/upload/")
fun fileUpload(@Part file:MultipartBody.Part): Call<FileUploadResponse>
响应数据类:
data class FileUploadResponse(
val created_at: String,
val file: String,
val id: Int,
val is_active: Boolean,
val updated_at: String,
val uuid: String )
我的电话是:
override fun fileUpload(context: Context,path: String): MutableLiveData<FileUploadResponse> {
val apiServices = rInstance.getRetrofitInstance()?.create(ApiServices::class.java)
val file = File(path)
val requestFile = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
val filePart = MultipartBody.Part.createFormData("file", file.name, requestFile)
Log.d("EWNMAP","path: $path, requestfile: $requestFile , filepart: $filePart")
val call =apiServices?.fileUpload(filePart)
call?.enqueue(object :Callback<FileUploadResponse>{
override fun onResponse(
call: Call<FileUploadResponse>,
response: Response<FileUploadResponse>
) {
if (response.isSuccessful){
fileUploaded.postValue(response.body())
Log.d("EWNMAP","Uploaded file: ${response.body()?.file}")
}else Toast.makeText(context,"File Upload not successful",Toast.LENGTH_LONG).show()
}
override fun onFailure(call: Call<FileUploadResponse>, t: Throwable) {
Toast.makeText(context,"File Upload failed",Toast.LENGTH_LONG).show()
}
})
return fileUploaded
}
我使用了 okhttp 记录器,所以在 logcat 中我得到了这些:
这里有什么问题?
那是存储权限问题