【发布时间】:2018-11-15 04:04:35
【问题描述】:
我正在尝试将图像从我的 android 应用程序上传到我服务器上的 php 脚本。在我的脚本中,我试图解码图像(使用 base64_decode),然后使用 file_put_contents() 将图像保存为我的目录中的文件。我的问题是当我在文件名末尾有 .jpg 时,文件“显示”为空。当我删除它以查看为图像编码添加的内容时,我看到了很长的字符串(特别是写入文件的 65214 个字节)。当我再次运行代码时,只是这次上传 $_POST['sent_image'] 而不解码,我得到了完全相同的文本字符串。
我不确定我做错了什么...最终目标是将图像保存在服务器上,以便可以在线其他地方查看,也可以检索它并返回到另一个活动我的安卓应用程序。
感谢所有建议!
注意:我也尝试过 imagecreatefromstring(),但这会导致写入 0 个字节。
我的代码:获取编码的 android 图像并尝试保存到服务器目录的 PHP:
<?php
include('inc.php');
if ((isset($_POST['searchinput'])) && (isset($_POST['newUnitStatus'])) && (isset($_POST['generalCause'])) && (isset($_POST['newUnitStatusComment'])) && (isset($_POST['newUnitStatusPhoto'])) && (isset($_POST['lexauser'])) && (isset($_POST['password']))) {
$sgref = "";
$searchinput = $_POST['searchinput'];
$newUnitStatus = $_POST['newUnitStatus'];
$generalCause = $_POST['generalCause'];
$newUnitStatusComment = $_POST['newUnitStatusComment'];
$lexauser = $_POST['lexauser'];
$pass = $_POST['password'];
if ((strpos($searchinput, "/") !== false)) {
$barcodesplit = preg_split('/\D/im', $searchinput, 4);
$sgref = $barcodesplit[0];
$lineitem = $barcodesplit[1];
$unitnumber = $barcodesplit[2];
$totalunits = $barcodesplit[3];
$unitname = $sgref."-".$lineitem."-".$unitnumber."_of_".$totalunits;
$photo = $_POST['newUnitStatusPhoto'];
$decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
$decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$fileName = "".$unitname."_rej";
$target = '../LEXA/modules/bms/uploads/';
$newFile = $target.$fileName;
$docType = "Reject";
$success = file_put_contents($newFile, $newUnitStatusPhoto);
if($success === false) {
$response['message'] = "Couldn not write file.";
echo json_encode($response);
} else {
$response['message'] = "Wrote $success bytes. ";
echo json_encode($response);
}
} else {
$sgref = $searchinput;
$response['message'] = "I'm sorry, but you must enter a unit's uniqueid value to add a unit exception. Please view the siblings for this SG and pick the unit you need. Then you can add the new status.";
echo json_encode($response);
}
} else {
$response['message'] = "Your search value did not get sent. Please try again.";
echo json_encode($response);
}//End logic for post values.
?>
谢谢!
【问题讨论】:
-
哇,没关系...当我将图像转换为 base64 时,我的问题实际上出在我的 android 代码上。我有“newUnitStatusContext = Base64.encodeToString(b, Base64.URL_SAFE);”而不是“newUnitStatusContext = Base64.encodeToString(b, Base64.DEFAULT);”
-
您使用 $_POST 而不是 $_FILES 有什么原因吗?
-
我正在用我的图片发送其他数据
-
我对此比较陌生,所以如果 $_FILES 在访问其他值方面也比 post 更好,我很想了解更多
-
如果你正在做的事情是有效的,那么继续做你正在做的事情。
标签: php image file-put-contents