无法将从相机单击的图像上载到服务器



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

($_File(从服务器单击图像并上传后的JSON响应

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

($_File(从Gallery拾取图像并上传后的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)
}
}
}

Gallery意向

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())
}
})
}

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

如果要上载大于设置大小的文件,只需打开php.ini文件即可增大大小。

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

upload_max_filesize = 50M    

而且PHP将接受的POST数据的最大大小是8Mb。如果要扩展它,请搜索post_max_size并增大大小。

最后,不要忘记重新启动Apache服务器。

最新更新