2018-03-28手机端上传图片,手机上传图片即时浏览,HTML5 图片上传(pc ,手机都能适配)

您现在的位置是: 首页 > PHP技术 > 手机端上传图片,手机上传图片即时浏览,HTML5 图片上传(pc ,手机都能适配)

1131次阅读

该代码可实现电脑、手机以及微信端图片上传,可即时进行浏览,图片上传后返回图片路径 

一、我们先来看看效果图


1.png


二、前端HTML5代码——index.html


<!DOCTYPE html>
<html>

   <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
      <link rel="stylesheet" type="text/css" href="./css/reset.css" />
      <link rel="stylesheet" type="text/css" href="./css/icon.css" />
      <link rel="stylesheet" type="text/css" href="./css/public.css" />
      <link rel="stylesheet" type="text/css" href="./css/custom.css" />
      <link rel="stylesheet" type="text/css" href="./css/layout.css" />
      <title>上传图片</title>
      <style type="text/css">
         .info-wrapper {
            padding: 0 15px;
            padding-bottom: 40px;
            min-height: 100%;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
         }
         
         .info-wrapper .input-wrap {
            position: relative;
            padding: 20px 0;
            border-bottom: 1px solid #e8e8e8;
         }
         
         .info-wrapper .input-wrap.select .icon {
            position: absolute;
            right: 0;
            top: 50px;
         }
         
         .info-wrapper .input-wrap .text {
            font-weight: 700;
         }
         
         .info-wrapper .input-wrap .text em {
            margin-left: 8px;
            font-size: 12px;
            color: #e64340;
         }
         
         .info-wrapper .input-wrap .input {
            position: relative;
            width: 100%;
            padding-top: 20px;
            margin-top: 0;
            border: none;
            background-color: transparent;
            z-index: 2;
         }
         
         .info-wrapper .input-wrap.code .btn {
            position: absolute;
            top: -5px;
            width: auto;
            line-height: 1;
            right: 0;
            margin: 0;
            padding: 5px 10px;
            margin-top: 20px;
            background-color: transparent;
            color: #333;
            font-size: 14px;
            font-weight: 700;
         }
         
         .info-wrapper .input-wrap .arrow {
            position: absolute;
            right: 0;
            top: 54px;
            font-size: 15px;
         }
         
         .info-wrapper .tips {
            position: relative;
            margin-top: 10px;
            margin-bottom: 30px;
            padding-left: 20px;
            line-height: 18px;
            color: #f96e53;
         }
         
         .info-wrapper .tips .icon {
            display: inline-block;
            position: absolute;
            left: 0;
            width: 16px;
            height: 16px;
            background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAEFklEQVR4Xu2aUVZaMRBAZ/KOPP9qV1C6guoK1BUUof/qf3niCtQVyAH/xf9CcQXSFdSuoHQFxT+g52V68oAeqmCSlwkiPL445yWZzM3MZDIJwpr/cM31hwxAZgFrTiBzgTU3gCwIZi6wKBcYVgrbUga7gigvAbdnyUWkDgH2QhHfYrXdXcTcvFqAUppicQIIBQDcslGIgLqCoA2BvMlV2/c2fW3aegEwjEqHBFABgJkrbTNB1ZYIOgHhxcbVl45tX117VgCJmcfBJSLs6QSn+k7QzgXxKad7sAEYRMUzADxPpZhVJ+ohwWmu3mpYdZvT2BkAVQpbwzi4Hvn5An9EjbDeOnaV6AQgUV4Gd1y+bq0MUSMXSOUSPeu+4w6pAby48hONHS0hNYB+uXTnLdjZLqcDhFQABlHxHADPbOf5uD0RfUOALUD84DoWEh2nCYzWAJLkRgbfXSdMRKeb9VZVjcMDlHo5IXdst0hrAIOopJR3TnDCWvOf7D+fP+1JQSqYuv0I2mG9eWAziBWAYbl4RIjXNgLmtfUCAACExH2bjNEKQD8q/kTA/DIDUGnzZr25bzpHYwCDz6UCCPhqOrCunS8LUHJzIn5vGgvMAUQllXoe6hQz/e4TAABdhLWWUVpuAaD42/ZI+xwMvwDgPqw1d0wWwwgAW5SempFnAMoN3pqkyEYAePbp/9fDNwCQcBBeNds6KzAEwOv/alLeARjGASMA/XKxg4i7Opo23/0DgJuw1jzSzWllAahzxma9pa1MGQEYRCXSkbT97tsCMgCcFvAaYwCrBfgAMJ2u+sgzABiD4IA5DU7ixbiep/76qSuapcOGQZCnAmQbKJ3acyZCnkzUST9dZ9ZUWAkblEs9QHijE2z+nS5QyCRVJRmok9tH876alkQ/wnrLqGpl5AIJAN448CRL4w20Zv6v9DIHwFkQmeGfnAcuLwURRatfLnYR8Z2rqU5XhCdjDaNSlQBOGMY2SoEncowtINmumIqi6u4/FHJ/UrYaldrFHUfBxWtRdGwFTCdD6gHh6L6f72L1Nqw1rS5prSwgsQKmixFXU3/Sn+AhF8R5kyrQdF9rAKMdYQkTI8PE5zG4VADG26Law/n2bjeTMCp+zBKRGsDoYYTocFxsuuluduiZJyM1gCSDe3kINzkRV2z93jkGTA8wfiihLk0W7Q6pzZ4VwGSwfrlYQcRLR3PWdyd4QKBKmrcArDFg1mCjZ3Kiyl1BnpJ1OzZ5tlekTjFg3nKpjFECHHGBUOWtgMS5zbW33pRGLbwAmAgfJ00VICjYHqWJ6JdAbIOIG6/uqewz7rEnEPOSaM5jaeggQXcjkB3T623TlfayDboKX4b+Xl1gGRTUzSEDoCO06t8zC1j1Fdbpl1mAjtCqf197C/gL/XEHX9ywz5cAAAAASUVORK5CYII=) no-repeat;
            background-size: 100% 100%;
         }
         
         .info-wrapper .input-wrap .pic-wrap {
            margin: 0 -10px;
         }
         
         .info-wrapper .input-wrap .pic-wrap .list {
            padding: 5px;
            font-size: 0;
         }
         
         .info-wrapper .input-wrap .pic-wrap .list .item {
            display: inline-block;
            width: 33.333%;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            padding: 5px;
            font-size: 14px;
         }
         
         .info-wrapper .input-wrap .pic-wrap .list .img-wrap {
            position: relative;
            width: 100%;
            padding-bottom: 100%;
         }
         
         .info-wrapper .input-wrap .pic-wrap .list .img-wrap .img {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
         }
         
         .info-wrapper .input-wrap .pic-wrap .list .img-wrap .file {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
         }
         
         .info-wrapper .input-wrap .pic-wrap .list .img-wrap .close {
            display: block;
            position: absolute;
            width: 15px;
            height: 15px;
            right: 5px;
            top: 5px;
            background: url(data:image/png;base64,iVBORw0KGg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ssHolsgm4SHAh2EA3uJ13R0g4lNdeGr11jU4r8en3xyc3eQGhX+zsdRl2UZE73HYMBVAWd0svqcLpbTaZYAP+yWPE0CqEMzLZZNQHvgQTckE8F2jPGVdNvgHIUAW8KJ5ryWZTTyzVA/YBJ6DUBFKJmDT6nIdMMqbVNAxIgv8os0ySSCAT6Usg5vWeQfmfjJlHSVn+HUZyxml1aELl8GChVC2yMkWSjoep1KHiC4LlcLZ4JcaQVkyqwBTLSOkcFGbIXXwS3NHtWlwaDujtIkMnsgtZDusAT6ys5i0mowEsR3mH1UTFSqupQ/+XjLzREWyL5tZq1AF08fmhLWtpsTMwUfyVKIW86bVNg5YPCVmIylqC/zCaJlktrVqrSRFhQw1EkT3efY466baXjetljVVuQBqjQNxVdf8YCSaS8lOTcEvI0LKgWZ4fC+28Zq/lIMRbfWVkgG2BX5Jwnx+3Pr83yCOVn8bT3e1KdtbLLcWDkdXsz3DhnsOgOIA095vVS2aaBfp4Sg3VtsLgHwg6Nu5HS6njQdG4veRtW+srY7+SgxYdGvbfe15gXlLmRckYiSUkCg1B5SnBb7za03Y2t3mTZekvKK3o3kAmJWlOwpYW/mSFO/MJNCYGWu/du5rcgsTrOtv+9iyW9S9KBmLB6UnKrNRqZXgCY/WhG284J15V5h3ZUt/q5ltp5QK+NRlUNa91Z2YHYzSVlTB5yJAeML3cHk6Y84nWVOaAvFK0ZOZ/vYtkXSHNO8U+mRmGRgfwx644uJTwafKanOFixxgrFPKo6m4SaFsFs/mCs3fy2mgOyLoph2vq1EXyweoVkiWi66sdjF8OFkSEXRHgL0fp0HvQR9OxsmIdpIdAuwWddQmjrLCp7N9U+AL23MHQRVPETlGhI7YHitci9vYZnQ73CHob/XjaRkI8bb4UeVojpU2ErQpej6f9BI+uvz5PAL6hOA5NPOqX2cDWyMts+9/WYyaO4iKar0AAAAASUVORK5CYII=) no-repeat;
            background-size: 100% 100%;
         }
      </style>
   </head>

   <body>
      <div class="page bgf">
         <div class="info-wrapper">
            <div class="form">
               <div class="input-wrap">
                  <div class="text">预签保费<em>*</em></div>
                  <div class="pic-wrap">
                     <ul id="piclist" class="list">
                        <li class="item upload">
                           <div class="img-wrap">
                              <img class="img" src="./img/upload.png" />
                              <input id="upload" class="file" type="file" value="" accept="image/*" />
                           </div>
                        </li>
                     </ul>
                  </div>
               </div>
               <div class="input-wrap">
                  <a id="submit" href="javascript:;" class="btn btn-primary" style="margin-top: 30px;">确定提交</a>
               </div>
            </div>
         </div>
      </div>
      <script id="tpl_upload" type="text/html">
         <li class="item">
            <div class="img-wrap">
               <img class="img" src="{{src}}" />
               <span class="close expand"></span>
            </div>
         </li>
      </script>
      <script src="./js/jquery.min.js"></script>
      <script src="./js/tools.js"></script>
      <script type="text/javascript">
         $(function() {

            var thumb = '';
            var upload_url = 'http://test.whmblog.cn/upload.php';

            var $upload = $('#upload'),
               $piclist = $('#piclist');
            $('#submit').click(function() {

               if(thumb!=''){
                  $.ajax({
                     type: "POST",
                     url: upload_url,
                     data: {
                        thumb: thumb
                     },
                     dataType: "json",
                     success: function(res){
                        Tools.toast(res.result.message);
                     }
                  });
               }else{
                  Tools.toast('请上传图片');
               }

            });

            $upload.change(function() {
               var fileSize = 10 * 1024 * 1024;
               var files = this.files[0];
               var _this = this;

               if(!/\.(gif|png|jpeg|JPEG|jpg|GIF|PNG|JPG)$/.test(files.name)) {
                  alert('请从相册选择图片或者直接拍照上传');
                  source.value = "";
                  return false;
               }

               if(files.size > fileSize) {
                  t.alert({
                     msg: '照片过大,请上传10M以下的照片',
                     icon: true
                  });
                  return false;
               }

               var reader = new FileReader();
               reader.readAsDataURL(files);
               reader.onload = function(e) {
                  thumb = this.result;
                  var _html = $('#tpl_upload').html().replace('{{src}}', this.result);
                  $(_this).parents('.item').before($(_html));
                  $(_this).parents('.item').hide();
               }
            });

            $piclist.delegate('.close', 'click', function() {
               $(this).parents('.item').remove();
               $("#piclist").find('.upload').show();
               thumb = '';
            })
         })
      </script>
   </body>
</html>


三、php图片上传代码 ——upload.php

<?php



if(empty($_POST['thumb'])){
    show_json(0, '图片不能为空!');
}

$path = '/upload/'.date('Y').'/'.date('m').'/'.date('d').'/';
$_root_path = $_SERVER["DOCUMENT_ROOT"].$path;

if(!is_dir($_root_path))// 如果文件上传目录不存在
{
    mkdir($_root_path, 0777, true);
}

$thumb = '';
$ret = createBase64($_POST['thumb'],$_root_path,time().mt_rand(100000,999999));
if($ret['state']!==1)
{
    show_json(0, $ret['err']);
    exit;
}
else
{
    $thumb = getCurrentServerName().$path.$ret['filename'];
    show_json(1, array('img_url'=>$thumb,'message'=>'上传图片成功'));
}



/*
* Base64生成图片文件,自动解析格式
*/
function createBase64($base64, $path, $filename) {

    $resinfo = array();
    //匹配base64字符串格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
        //保存最终的图片格式
        $postfix = $result[2];
        $base64 = base64_decode(substr(strstr($base64, ','), 1));
        $filename = $filename . '.' . $postfix;
        $path = $path . $filename;
        //创建图片
        if (file_put_contents($path, $base64)) {
            $resinfo['state'] = 1;
            $resinfo['filename'] = $filename;
        } else {
            $resinfo['state'] = 2;
            $resinfo['err'] = 'Create img failed!';
        }
    } else {
        $resinfo['state'] = 2;
        $resinfo['err'] = 'Not base64 char!';
    }

    return $resinfo;
}


function show_json($status = 1, $return = NULL) {

    $ret = array('status' => $status);
    if (!is_array($return)) {
        if ($return) {
            $ret['result']['message'] = $return;
        }

        exit(json_encode($ret));
    } else {
        $ret['result'] = $return;
    }

    exit(json_encode($ret));

}


// 说明:获取当前页面的带http/https的域名
function getCurrentServerName()
{
    $pageURL = 'http';
    if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"];
    }
    return $pageURL;
}


四、完整代码下载