我正在尝试将多个图像上传到Cloudinary。使用Ajax使用第二个php文件将数据写入sql。上载时还需要对数据进行序列化,显示时还需要将其反序列化。进行序列化的原因是,上传图像时,我需要更多信息,即安全url,原始文件名等。下面是写在下面的php文件中的代码片段。
cloudinary.openUploadWidget({
cloud_name: 'username',
upload_preset: 'preset',
sources: ['local', 'camera'],
multiple: true,},
function (error, result) {
console.log(error, result);
const eventData = result.data;
if (result.event === "success") {
var user_id = <?php echo $user['user_id']; ?>;
var image_name = result.info.original_filename;
var image_url = result.info.secure_url;
var thumbnail_url = result.info.thumbnail_url;
$.ajax({
url: "save.php",
type: "POST",
data: {
image_url : image_url,
image_name : image_name,
thumbnail_url : thumbnail_url,
}
});
document.getElementById("images").innerHTML += '<li class="cloudinary-thumbnail active"><img src="'+result.info.thumbnail_url+'" data-src="'+result.info.thumbnail_url+'" ><input type="hidden" name="image_name[]" value="'+result.info.original_filename+'"><input type="hidden" name="image_url[]" value="'+result.info.secure_url+'"><h5>'+result.info.original_filename+'</h5></li>';
}
});}, false);
这是save.php
if ($_POST) {
$user_id = $_POST['user_id'];
$image_name = $_POST['image_name'];
$image_url = $_POST['image_url'];
$thumbnail_url = $_POST['thumbnail_url'];
$arraylength = $_POST['arraylength'];
$images = array();
for ($i=0; $i < sizeof($image_name); $i++) {
$images[$i]['name'] = $image_name;
$images[$i]['url'] = $image_url;
$images[$i]['thumbnail_url'] = $thumbnail_url;
};
try {
$stmt = $db->prepare("UPDATE images_collection SET images = :images WHERE user_id = :user_id");
$stmt->execute(array(
':images'=>serialize($images),
':user_id'=>$user_id
));
echo "true";
} catch (PDOException $e) {
echo $e->getMessage();
}
}