【发布时间】:2021-07-21 21:07:04
【问题描述】:
我在将图像上传到 PHP 服务器时遇到了一些问题。在这种情况下,首先我从图库中获取图像,然后将输出创建为 base64,然后使用流将 base64 转换为文件,然后将其上传到服务器。这是我的代码。
上传活动.kt
private fun updatePhoto(variable: String, file: Bitmap, userId: String) {
val encode = encodedImage(file)
val outputDir: File = this.cacheDir
val f = File.createTempFile(userId, ".jpeg", outputDir)
var fos: FileOutputStream? = null
try {
fos = FileOutputStream(f)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
try {
fos!!.write(encode)
fos.flush()
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
val builder = MultipartBody.Builder()
builder.setType(MultipartBody.FORM)
val requestFile = f.asRequestBody(getMimeType(f.path)?.toMediaTypeOrNull())
builder.addFormDataPart(variable, f.name, requestFile)
builder.addFormDataPart("userId", userId)
val apiService = ApiInterface.create()
val call = apiService.updatePicture(builder.build())
call.enqueue(object : Callback<UserModel> {
override fun onResponse(
call: Call<UserModel>,
response: retrofit2.Response<UserModel>?
) {
val jsonObject = response!!.body()
val returnedResponse = jsonObject!!.status
if (returnedResponse!!.trim { it <= ' ' } == "200") {
val intent = Intent(this@UploadPreviewActivity, ProfileActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
finish()
} else {
Toast.makeText(
this@UploadPreviewActivity,
"Terjadi kesalahan, harap coba kembali.",
Toast.LENGTH_SHORT
).show()
}
}
override fun onFailure(call: Call<UserModel>, t: Throwable) {
call.cancel()
Toast.makeText(
this@UploadPreviewActivity,
"Harap periksa koneksi internet anda",
Toast.LENGTH_LONG
).show()
}
})
}
Interface.kt
@POST("user-update-picture")
fun updatePicture(@Body requestBody: RequestBody): Call<UserModel>
上传.php
function resize_image($file) {
$src = imagecreatefromstring($file);
if (!$src) return false;
$width = imagesx($src);
$height = imagesy($src);
$newwidth = $width*0.5;
$newheight = $height*0.5;
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ob_start();
imagejpeg($dst);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function decodeImage($picturePath, $dir, $dir_thumb, $userId){
$image = str_replace('data:image/png;base64,', '', str_replace('[removed]', '', $picturePath));
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$data2 = base64_decode($picturePath);
$thumb = $this->resize_image($data2);
$file = './files/images/'.$dir.'/'.$userId.'.jpg';
$upload = file_put_contents($file, $data);
$file2 = './files/images/'.$dir_thumb.'/'.$userId.'.jpg';
$upload2 = file_put_contents($file2, $thumb);
}
public function picture_post(){
date_default_timezone_set('Asia/Jakarta');
$Date = date('Y-m-d H:i:s');
$userId = filter_var($this->post('userId'), FILTER_SANITIZE_NUMBER_INT);
if (isset($_FILES['userPhotoPath']['tmp_name']) && !empty($_FILES['userPhotoPath']['tmp_name']) && $_FILES['userPhotoPath']['tmp_name']!=NULL) {
$photoPath = $_FILES['userPhotoPath']['tmp_name'];
$photoType = $_FILES['userPhotoPath']['type'];
$photoData = file_get_contents($photoPath);
$userPhotoPath = 'data:' . $photoType . ';base64,' . base64_encode($photoData);
if(file_exists("./files/images/users/".$userId.".jpg")){
$unlink = unlink("./files/images/users/".$userId.".jpg");
}
if(file_exists("./files/images/users_thumb/".$userId.".jpg")){
$unlink2 = unlink("./files/images/users_thumb/".$userId.".jpg");
}
$this->decodeImage($userPhotoPath, 'users', 'users_thumb', $userId);
}else{
$userPhotoPath = NULL;
}
}
然后,当我从 android 上传文件时,我在 Okhttp 日志中收到此错误
消息:imagecreatefromstring():数据不是可识别的格式 回溯: 函数:imagecreatefromstring
我不知道为什么,因为我的 PHP 代码可以与我的 Web 版本的应用程序一起使用,使用相同的上传方法使用 javascript
【问题讨论】:
-
你为什么将它隐藏为 basesix4 ?只需在本地目录中写入文件并将路径传递给改造
-
我会在上传之前手动编辑图像,如旋转等@Manikandan
-
那么……我们可以将编辑后的图像保存在本地目录中……并将路径发送到服务器。
-
是的,我这样做了,但仍然从服务器返回错误。
标签: php android kotlin file-upload retrofit2