【问题标题】:Unable to upload image clicked from camera to server无法将点击的图像从相机上传到服务器
【发布时间】:2020-03-04 19:01:16
【问题描述】:

我正在尝试从相机点击后将图像上传到服务器,但服务器返回

($_File) 从服务器点击图片并上传后的 JSON 响应

{
   "data":78,
   "status":true,
   "files":
   {
      "photo": 
      {
         "name":"IMG_20191108_115642_5386652903586463966.jpg",
         "type":"",
         "tmp_name":"",
         "error":1,
         "size":0
      }
    }
  }

($_File) 从图库中挑选图片并上传后的 JSON 响应

    {
     "data":79,
     "status":true,
     "files":
         {
           "photo": 
              {
               "name":"Screenshot_20191108_081937_com.instagram.android.jpg",
               "type":"*\/*",
               "tmp_name":"C:\\xampp\\tmp\\php50A6.tmp",
               "error":0,
               "size":518164
              }
         }
   }
    

     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pharmacy)
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
            PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
            PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, permission, REQUEST_PERMISSION)
        }
    next.setOnClickListener {

            if (prescriptionid == "") {
                Toast.makeText(
                    applicationContext,
                    "Select/Upload Prescription First",
                    Toast.LENGTH_LONG
                ).show()
            } else {
                intent = Intent(applicationContext, SelectAddressActivity::class.java)
                imageFilePath = ""
                imageView.setImageResource(R.drawable.ic_image)
                imagedisplay.visibility = View.GONE
                startActivity(intent)
            }
        }

        if (imageFilePath == "") {
            imagedisplay.visibility = View.GONE
        } else {
            imagedisplay.visibility = View.GONE
        }
     }

相机意图

private fun openCameraIntent() {
        val pictureIntent = Intent(
            MediaStore.ACTION_IMAGE_CAPTURE)
        if (pictureIntent.resolveActivity(getPackageManager()) != null)
        {
            try
            {
                photoFile = createImageFile()
            }
            catch (ex:IOException) {}// Error occurred while creating the File
            if (photoFile != null)
            {
                val photoURI = FileProvider.getUriForFile(this, packageName+".provider", photoFile)
                pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI)
                startActivityForResult(pictureIntent,CAMERA_REQUEST_CODE)
            }
        }
    }

画廊意图

private fun pickFromGallery() {
        //Create an Intent with action as ACTION_PICK
        val intent = Intent(Intent.ACTION_PICK)
        // Sets the type as image/*. This ensures only components of type image are selected
        intent.type = "image/*"
        //We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
        val mimeTypes = arrayOf("image/jpeg", "image/png")
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
        // Launching the Intent
        startActivityForResult(intent, GALLERY_REQUEST_CODE)
    }
 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        imagedisplay.visibility = View.VISIBLE
        when (requestCode) {
            CAMERA_REQUEST_CODE -> {
                if (resultCode == Activity.RESULT_OK) {
                    correct.visibility = View.VISIBLE
                    imageView.setImageBitmap(setScaledBitmap())
                }
            }
           GALLERY_REQUEST_CODE -> {
                //data.getData returns the content URI for the selected Image
                if (resultCode == Activity.RESULT_OK) {
                    correct.visibility = View.VISIBLE
                    var selectedImage = data!!.data as Uri
                    var filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
                    // Get the cursor
                    var cursor = getContentResolver().query(
                        selectedImage,
                        filePathColumn, null, null, null
                    );
                    // Move to first row
                    cursor!!.moveToFirst();
                    //Get the column index of MediaStore.Images.Media.DATA
                    var columnIndex = cursor.getColumnIndex(filePathColumn[0])
                    //Gets the String value in the column
                    var imgDecodableString = cursor.getString(columnIndex)
                    cursor.close()
                    // Set the Image in ImageView after decoding the String
                    Log.i("filepath", imgDecodableString)
                    imageFilePath = imgDecodableString
                    imageView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString))

                }
            }
            else -> {
                Toast.makeText(this, "Unrecognized request code", Toast.LENGTH_SHORT).show()
            }
        }
    }

创建图像文件的代码


    @Throws(IOException::class)
    private fun createImageFile(): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES) as File
        return File.createTempFile(
            "IMG_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            imageFilePath = absolutePath
        }
    }

上传图片到服务器的代码


       val file = File(imageFilePath)
       //creating request body for file
       var requestBody = file.asRequestBody("*/*".toMediaTypeOrNull())
//        val requestFile = file.asRequestBody("*/*".toMediaTypeOrNull())
       var photo = MultipartBody.Part.createFormData("photo", file.name, requestBody)
//        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
       Log.e("requestFile", imageFilePath)

       val uploadImage =
           RetrofitCall.provideRetrofit().create(uploadPrescriptionApi::class.java)

       uploadImage.uploadPrescription("Bearer ".plus(sharedPreference!!.token.toString()), photo)
           .enqueue(object : Callback<UploadPhototPOJO> {
               override fun onResponse(
                   call: Call<UploadPhototPOJO>,
                   response: Response<UploadPhototPOJO>
               ) {
                   if (response.body()!!.status!!) {
                       progressDialog!!.dismiss()
                       prescriptionid = response.body()!!.id.toString()
                       Log.i("id", prescriptionid.toString())
                   } else {
                       Toast.makeText(
                           applicationContext,
                           "Oops Something Went Wrong!! Try again",
                           Toast.LENGTH_LONG
                       ).show()
                       progressDialog!!.dismiss()
                   }
               }

               override fun onFailure(call: Call<UploadPhototPOJO>, t: Throwable) {
                   // handle execution failures like no internet connectivity
                   Log.i("Faliure", t.toString())
               }
           })

   }

【问题讨论】:

  • 相机图像可能太大。在上传之前尝试压缩您的图片。
  • 图片大小约为 4 mb
  • 通过降低相机分辨率设置来确认尝试使用较小尺寸的图像
  • 我使用 Bitmap Compress 压缩了图像,但现在图像像素化了

标签: android kotlin retrofit


【解决方案1】:

上传文件的最大允许大小为 2Mb。正如您在comment 中提到的,上传的照片大小为 4Mb。

如果要上传大于设置大小的文件,只需打开php.ini 文件以增加大小。

在您喜欢的任何一种文本编辑器中打开C:/xampp/php/php.ini 文件。搜索 upload_max_filesize 并将其更改为大小。例如,50Mb

upload_max_filesize = 50M    

PHP 接受的最大 POST 数据大小为 8Mb。如果你想扩展它,搜索post_max_size并增加大小。

最后,别忘了重启 Apache 服务器。

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2021-04-30
    • 1970-01-01
    • 2018-01-19
    • 2017-09-09
    • 2021-12-23
    • 2015-09-24
    • 1970-01-01
    • 2023-01-08
    相关资源
    最近更新 更多