2

I am able to upload image using postman but while uploading image from android app. I am facing the error. please help me for the fix this error java.lang.NullPointerException: Cannot invoke "org.springframework.web.multipart.MultipartFile.getOriginalFilename()" because "file" is null.

Interface UploadService {
      @Multipart
    @POST("/uploadFile")
    suspend fun uploadFile(@Header("Content-Type") type: String,
                            @Part file: MultipartBody.Part,
                            @Part("fileName") fileName: RequestBody
    ): Call<UploadFileResponse>
}

Image upload method

    suspend fun uploadImage(context: Context, uri: Uri,imagePath:String?): Result<UploadFileResponse> {
        try {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            val client: OkHttpClient = OkHttpClient.Builder().
            addInterceptor(interceptor).build()
            val gson = GsonBuilder().setLenient()
                .create()

            val   service = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                 .baseUrl("http://10.0.2.2:9000/")
                .client(client)
                .build()
                .create(
                    UploadService::class.java
                )

            Console.debug(javaClass.simpleName,"ClassName:ShopOrderProductRepository FunctionName:uploadImage imagePath:${imagePath} file11:file11")
            var file:File?=null
            var imagePart: MultipartBody.Part?=null
            var reqFile: RequestBody?=null
            if(!imagePath.isNullOrEmpty()){
                val file1 = Uri.fromFile(
                    File(
                        context.cacheDir,
                        imagePath//getType(imagePath.path)//
                    )
                ).toFile()
                val file = File(context.cacheDir, "image12.jpg")
                file.createNewFile()
                file.outputStream().use {
                    context.assets.open("image12.jpg")
                }
                // file=File(imagePath?:"")
                //reqFile = RequestBody.create("image/*".toMediaTypeOrNull(), file)
                reqFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)

                imagePart = MultipartBody.Part
                    .createFormData(
                        name = "profile_image",
                        filename =file?.name,
                        body = reqFile!!//file.asRequestBody()
                    )

            }else{
                val stream = context.contentResolver.openInputStream(uri)
                //var requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), stream!!.readBytes())
                var bytes=stream!!.readBytes()
                Console.debug(javaClass.simpleName,"ClassName:ShopOrderProductRepository FunctionName:uploadImage imagePart:${imagePart} bytes:${bytes.size} bytes:${bytes.toString()}")

                // reqFile = RequestBody.create("image/*".toMediaTypeOrNull(), bytes)
                reqFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), bytes)
                imagePart = MultipartBody.Part
                    .createFormData(
                        name = "profile_image",
                        filename ="profile.png",//file?.name,
                        body = reqFile
                    )
            }
           val fileNameRequestBody = RequestBody.create("text/plain".toMediaTypeOrNull(), file?.name?:"")

            try {
                var response=    service?.uploadFile("multipart/form-data;boundary=" + System.currentTimeMillis(),imagePart,fileNameRequestBody)?.awaitResponse()
                if(response?.isSuccessful?:false){
                    return Result.Success(response?.body()!!)
                }else{
                    return Result.Error(Exception(response?.message()))
                }
            } catch (e: Exception) {
                ExceptionHandler.handle(e)
                return  Result.Error(Exception("Error busiCode:",e))
            }

        } catch (e: Exception) {
            ExceptionHandler.handle(e)
            return Result.Error(IOException("Error busiCode:registershops", e))
        }
    }
Ankush
  • 91
  • 6
  • Check out https://stackoverflow.com/questions/13303544/how-to-solve-nullpointerexception-error-in-android for tips on solving NullPointerException – Code-Apprentice Oct 02 '22 at 02:17
  • I am passing MultipartBody.Part object from My Android App . but I am getting null object on server side. – Ankush Oct 02 '22 at 02:29
  • I suggest you start by adding validation on the server side to prevent the NPE. And also determine why the server has a null object. Start at the line where the error happens and work backwards. – Code-Apprentice Oct 02 '22 at 02:42
  • See https://stackoverflow.com/a/56308643/115145 for how to create a `RequestBody` from a `Uri`. – CommonsWare Oct 02 '22 at 11:09

0 Answers0