php图片上传功能,实时显示上传的图片

8 篇文章 0 订阅
5 篇文章 0 订阅

工作中总会有需要自己写前端上传图片功能,特意保留一下自己感觉还好的前端上传图片代码
主要介绍了PHP上传图片显示缩略图功能代码,

前端html代码

<input type="hidden" name="pic" id="slide_img"  value="" data-style="height:84px;">
<a href="javascript:;" id="upload_box" class="addUpload"  onclick="addImage('#slide_img')" >
    <img width="84px;" src="/refund/img/upload.png"/>
</a>
<!--上传图片使用的form和显示样式-->
<script src="<{:C('CSSJSHOST')}>/wap/assets/js/upload_img/upload_img.js"></script>
<form name="form1" method="post" action="/my/upload_img_callback.html" target="imageUpload"
      enctype="multipart/form-data" style="display:none;">
    <input type="file" name="imageFile" id="imageFile"  accept="image/*" onchange="uploadFile(this)">
    <input type="hidden" name="imageTag" id="imageTag">
</form>
<iframe id="imageUpload" name="imageUpload" src="about:blank" style="display:none"></iframe>
<div class="uploadBackdrop"></div>
<div class="mwrap" id="uploadPopup" style="display:none">
    <div class="inner">
        <div class="spinner">
            <div class="rect1"></div>
            <div class="rect2"></div>
            <div class="rect3"></div>
            <div class="rect4"></div>
            <div class="rect5"></div>
        </div>
        <p>正在上传</p>
    </div>
</div>
<!---->

addImage() 函数是上传图片事件,里面的参数是input 标签,到时候图片上传完之后要把值赋值到改input标签

JS 代码

 
/**
 * 添加图片点击
 * @param id
 */
function addImage(id) {
    $('#imageFile').attr('container', id).click();
    $('#imageTag').val(id);
}
/**
 * 添加图片点击
 * @param id
 */
function addImageChapter(id,book_id) {
    $('#imageFile').attr('container', id).click();
    $('#imageTag').val(id+'_'+book_id);
}
/**
 * 更换图片点击
 * @param el
 */
function changeImage(el) {
    if (confirm('你是要换一张么?')) {
        $(el).siblings(".hidden").val('');
        $(el).siblings(".addUpload").show();
        $(el).remove();
    }
}

/**
 * 上传文件
 * @param input
 */
function uploadFile(input) {
    if (input.files.length > 0) {
        var form1 = document.form1;
        form1.submit();
        startUploadPopup();
    }
    input.value = null;
}

/**
 * 上传成功
 * @param data
 */
function uploadSuccess(data) {
    closeUploadPopup();
    // $('.addUpload').hide();
    var container = $('#imageFile').attr('container');
    console.log(container)
    if (container == '.pics') {
        $(container).append('<li class="img_node"><input name="chapter_imgs[]" type="hidden" value="' + data + '"><img src="' + data + '" alt=""><span class="close" οnclick="closePic(this)"></span><span class="close left" οnclick="leftPic(this)"></span><span class="close right" οnclick="rightPic(this)"></span></li>');
    } else {
        $('#slide_img').hide();
        $(container).hide();
        $(container).siblings(".addUpload").hide();
        $(container).val(data);
        $(container).parent().append('<a href="javascript:void(0);" class="uploadPics" οnclick="changeImage(this)"><img src="' + data + '" style="'+$(container).data('style')+'"></a>');
    }
}

function substrUrl(url) {
    var index = url.indexOf('http://img.ai7.com/');
    if (index != -1) {
        return url.substring(index + 19);
    } else {
        return url;
    }
}
function uploadError(data) {
    closeUploadPopup();
    alert(data);
}
function startUploadPopup() {
    $("#uploadPopup p").text('正在上传');
    $("#uploadPopup,.uploadBackdrop").show();
}
function closeUploadPopup() {
    $("#uploadPopup,.uploadBackdrop").hide();
}
function closePic(el) {
    $(el).parent().remove()
}
function leftPic(el) {
    if($(el).parent().prev().hasClass('img_node'))
        $(el).parent().insertBefore($(el).parent().prev());
}
function rightPic(el) {
    if($(el).parent().next().hasClass('img_node'))
        $(el).parent().insertAfter($(el).parent().next());
}
 
 

PHP代码



/**
 * 上传图片
 * @return mixed
 */

function upload_img_callback()
{
    header('Content-Type: application/javascript; charset=utf-8;');
    $imgTag = input('imageTag');
    $subPath = 'default';
    if ($imgTag == '#thumb') {
        $subPath = 'book';
    } elseif ($imgTag == '#slide_img') {
        $subPath = 'slide';
    } elseif ($imgTag == '#active_img') {
        $subPath = 'active';
    }
    $info = uploadImg('imageFile', $subPath);
    if ($info['status'] == 1) {
        echo "<script>parent.uploadSuccess('" . $info['msg'] . "')</script>";
    } else {
        echo "<script>parent.uploadError('" . $info['msg'] . "')</script>";
    }
}


// 生成文件路径
function mkDirs($path)
{
    $array_path = explode("/", $path);
    $_path = "";
    for ($i = 0; $i < count($array_path); $i++) {
        $_path .= $array_path[$i] . "/";
        if (!empty($array_path[$i]) && !file_exists($_path)) {
            mkdir($_path, 0777);
        }
    }
    return true;
}


/**
 * 上传图片
 */
function uploadImg($input = 'image', $subPath = 'default')
{
    $upload_dir = dirname(dirname(dirname(__DIR__))) . '/';
    $picnowurl = "图片域名"; // 图片域名
    $file = $_FILES[$input];
    if ($file == null) {
        return array('status' => -1, 'msg' => '上传文件不存在');
    }
    $name = $file["name"];// 文件名
    $type = $file["type"];// 文件类型
    $size = $file["size"];// 文件大小
    $tmp_name = $file['tmp_name'];
    $error = $file["error"];
    /上传的图片浏览器的类型不同,$type的值也不同
    if (!in_array($type, array('image/pjpeg', 'image/jpeg', 'image/gif', 'image/x-png','image/png'))) {
        return array('status' => -1, 'msg' => '不支持的图片文件类型');
    }

    上传文件路径
    $time = date("YmdHis");
    $picture_name = strstr($name, "."); //通过strstr()函数截取上传图片的后缀
    $picallname = $subPath . $time . rand(1000, 9999);
    $diryearmonth = date("Ym");
    $dirday = date("d");
    $savePath = $upload_dir . "/uploads/" . $subPath . "/" . $diryearmonth . "/" . $dirday . "";
    $fileupname = "/uploads/" . $subPath . "/" . $diryearmonth . "/" . $dirday . "/" . $picallname . $picture_name;
    if ($error == '0') {
        // 上传到当前服务器
//        $this->mkDirs($savePath);
//        move_uploaded_file($tmp_name, $upload_dir . $fileupname); // //上传图片的函数()

        $res = $this->imgToBase64($tmp_name, $subPath); // 使用base64上传到远程
        return array('status' => 1, 'msg' => $res);
    }
    return array('status' => 1, 'msg' => $picnowurl . $fileupname);
}


/**
 * 获取图片的Base64编码(不支持url)
 * @date 2017-02-20 19:41:22
 * @param string $img_file 传入本地图片地址
 * @param string $subPath 存储图片路径
 * @return string
 */
function imgToBase64($img_file='', $subPath='')
{
    $img_url = '';
    if (file_exists($img_file)) {
        $img_info = getimagesize($img_file); // 取得图片的大小,类型等
        $content = file_get_contents($img_file);
        if ($content) {
            $file_content = chunk_split(base64_encode($content)); // base64编码
            switch ($img_info[2]) {           //判读图片类型
                case 1:
                    $img_type = "gif";
                    break;
                case 2:
                    $img_type = "jpg";
                    break;
                case 3:
                    $img_type = "png";
                    break;
                case 6:
                    $img_type = "bmp";
                    break;
                default:
                    return false;
            }
            $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
            $post_data = array(
                'type' => $subPath,
                'file' => $img_base64,
            );
            $url = '/lm_upload_thumb.php';// 远程上传图片地址(base64上传文件)
            $res = json_decode(http_post($url, $post_data), true);
            if ($res['rtn'] == 1) {
                unlink($img_file);
            }
            $img_url = $res['data'];
        }
    }
    return $img_url; //返回图片的base64
}

lm_upload_thumb.php文件 -

base64上传图片方法


$subPath = ($_POST['type']);
$base64_image_content = $_POST['file'];

$back_data = array(
	'rtn'=>0,'data'=>'','msg'=>'no',
);
 
if (empty($base64_image_content) || !$subPath) { 
	echo json_encode($back_data);
	exit(); 
}
$document_root = dirname(__DIR__).'/app.com';
$path = local_path($subPath);
$path = trim($path, "/");
if (!file_exists($document_root . "/" . $path)){
    mkdir ($document_root . "/" . $path,0777,true);
}

$time = time();
// 将格式为base64的字符串解码
preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result);
$img_type = $result[2];
$picallname=$subPath.$time.rand(1000,9999);
$filename =  $picallname. ".{$img_type}"; 

$url_path = 'https://p.***.cn/' . $path . "/" . $filename;
if (!file_exists($document_root . "/" . $path."/".$filename)){   
    file_put_contents($document_root . "/" . $path."/".$filename, base64_decode(str_replace($result[1], '', $base64_image_content)));
}
 
$back_data['data'] = $url_path; 
$back_data['rtn'] = 1;
echo json_encode($back_data);
exit(); 

function local_path($subPath)
{
	$diryearmonth=date("Ym");
	$dirday=date("d");
	$path = "/uploads/lmcps/".$subPath."/".$diryearmonth."/".$dirday."";

    if (file_exists($path) === false) {
        mkdir('.' . $path, 0777, true);
        chmod('.' . $path, 0777);
    }
    return $path;
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的PHP代码示例,可以帮助你实现上商品图片到数据库并显示功能: 1. 创建一个包含以下字段的数据库表: ```sql CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `price` decimal(10,2) NOT NULL, `image` longblob NOT NULL, PRIMARY KEY (`id`) ); ``` 2. 创建一个HTML表单,其中包含一个文件上字段和其他商品信息: ```html <form action="add_product.php" method="post" enctype="multipart/form-data"> <label for="name">Product name:</label> <input type="text" name="name" id="name"><br> <label for="price">Price:</label> <input type="text" name="price" id="price"><br> <label for="image">Image:</label> <input type="file" name="image" id="image"><br> <input type="submit" value="Add product"> </form> ``` 3. 创建一个PHP脚本,用于处理文件上并将商品信息和图像数据存储到数据库中: ```php // 获取上的文件 $image = $_FILES['image']['tmp_name']; // 将文件转换为二进制数据 $imageData = file_get_contents($image); // 获取文件类型 $imageType = $_FILES['image']['type']; // 获取商品信息 $name = $_POST['name']; $price = $_POST['price']; // 将商品信息和图像数据存储到数据库中 $db = new mysqli('localhost', 'username', 'password', 'database'); $stmt = $db->prepare("INSERT INTO products (name, price, image) VALUES (?, ?, ?)"); $stmt->bind_param('sds', $name, $price, $imageData); $stmt->execute(); $stmt->close(); ``` 4. 创建一个PHP脚本,用于检索并显示商品信息和图像数据: ```php // 获取商品ID $id = $_GET['id']; // 从数据库中检索商品信息和图像数据 $db = new mysqli('localhost', 'username', 'password', 'database'); $stmt = $db->prepare("SELECT name, price, image, type FROM products WHERE id = ?"); $stmt->bind_param('i', $id); $stmt->execute(); $stmt->bind_result($name, $price, $imageData, $imageType); $stmt->fetch(); $stmt->close(); // 显示商品信息和图像数据 echo "<h1>$name</h1>"; echo "<p>Price: $price</p>"; echo '<img src="data:' . $imageType . ';base64,' . base64_encode($imageData) . '">'; ``` 注意,这只是一个简单的示例,你需要根据自己的实际需求进行修改和调整。同时,需要注意的是,将图像存储在数据库中可能会影响性能,因此最好还是将图像存储在文件系统中,并将数据库中存储图像的字段设置为文件路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值