将镜像文件路径插入到PostgreSQL数据库中


Insert image file path into PostgreSQL database

我有一个移动应用程序,它发送一些数据到我的PHP web服务。该数据由一些文本项和一个base64编码的字符串(将被解码成图像)组成。

我想将文本数据存储到一些数据列中,然后是包含上传图像的文件路径的最终文本列。我有一个名为usersImages/的目录,这是我想存储用户收到的所有图像的地方,但是当我上传数据时,我的PHP脚本目前没有向数据库中插入任何内容。

PHP文件:

$conn = pg_connect("database_credentials");
/* GET DATA */
$name = $_POST['name'];
$s_name = pg_escape_string($name);
$description = $_POST['desc'];  
$s_desc = pg_escape_string($description);
$latitude = $_POST['lat'];
$longitude = $_POST['lng'];
$project = $_POST['project'];
$encoded_photo = $_POST['snap'];
echo $encoded_photo;
$photo = base64_decode($encoded_photo);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('usersImages/test.jpg', 'wb');
fwrite($file, $photo);
fclose($file);
$res = pg_query("INSERT INTO records (name, description, latitude, longitude, project, imagepath) VALUES ('$s_name', '$s_desc', '$latitude', '$longitude', '$project', '$file')");

我想做的:

我希望所有的数据都存储为文本,最后一列imagepath包含我刚刚上传的图像的路径,但我目前没有成功。什么好主意吗?

我相信你遇到的问题是"imagepath"列,你存储的$file变量是fopen('usersImages/test.jpg', 'wb');。您不能将函数调用存储到列单元格中,相反,您应该存储适合您需要的数据类型(因为您希望存储路径字符串,所以varchar应该可以正常工作)。

我假设你想做的只是存储路径,例如:

$filePath = "usersImages/test.jpg";
$res = pg_query("INSERT INTO records (name, description, latitude, longitude, project, imagepath) VALUES ('$s_name', '$s_desc', '$latitude', '$longitude', '$project', '$filePath')");

(只要你正确连接到你的数据库,这个方法应该工作)

我甚至可以进一步建议您只存储变量名称以节省空间并硬编码始终相同的变量....例如,如果文件夹总是相同的,图像类型总是JPG,你可以存储$filePath = "test";和改变你的加载代码与硬编码的变量,而不仅仅是一个数据库查询。

至于你的另一个问题,关于实际上传图片到你的网站,这是很难告诉你一个确切的答案,因为你没有提供相关的代码;但是,由于上传技术不正确,看起来您正在获得虚假文件。您应该尝试这样的方法,而不是使用fopen,fwrite,fclose方法。

<input type="file" name="file" id="file"> // In your form (seperate from PHP)
$filePath = "userImages/test.jpg";  //setting file path
$success = move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $filePath); //actually storing the file into your file-system into the selected path