创建文件 index.html
编写前端代码,通过POST把图片提交到PHP后端去处理
<div>
<form action="index.php" method="post" enctype="multipart/form-data" >
<input type="file" name="file" id='file'>
<input class="btn btn-primary" name="submit" type="submit">
</form>
</div>
相同目录下创建 index.php
PHP接收前端提交的图片之后,然后函数编码成base64字符串!
把字符串保存到数据库,就可以把临时图片删除了,此时服务器并没有图片!
但通过调用数据库的base64字符串就可以把图片再次显示出来
$img_path = './img/1.jpeg';
if(move_uploaded_file($_FILES['file']['tmp_name'],$img_path)){
$base64 = base64_encode(file_get_contents($img_path));
//输出编码的字符串
echo $base64;
//保存$base64字符串到数据库
//sql ..
//删除临时图片
unlink($img_path);
//读取$img,展示base64加密的图片
$img = "<img src='data:image/png;base64,". $base64 ."'>";
echo $img;
//返回正确信息
echo 'success';
}else{
echo 'error';
}
编码后的字符串后是如何在网页上展示的呢?具体格式参考如下方式
对应gif、png、jpeg
data:image/gif;base64,
data:image/png;base64,
data:image/jpeg;base64,