美文网首页
上传图片

上传图片

作者: TianTongBo | 来源:发表于2020-01-09 11:59 被阅读0次

    思维导图


    62036185-595a6630913f2_articlex.png
    <style>
    .imgUp1{width: 150px;
        height: 80px;
        border: 1px dashed #eee;
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .imgUp1 img{
    position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        border-radius: 5px;
        width: 100%;
        height: 100%;
        border: none;
    }
    .imgUp1 span{
        font-size: 12px;
        color: #333;
    }
    <style>
     <div class="pubMgAddConList pubMgAddConListImg">
            <span>LOGO</span>
              <div>
                    <div class="imgUp1">
                         <img  src="{if !empty($pubInfo)}{$pubInfo['logo']}{/if}"  id="logoImg1"/>
                         <span>十</span>
                     </div>
               </div>
               <input type="file" id="idcard1" name="image" accept="image/*" onchange="handleInputChange(event,$('#logoImg1'))" style="display: none;">           
     </div>
    <script> 
    $(".imgUp1").click(function () {
            $("#idcard1").click()
      });
    //利用函数之间去传值
     // 全局对象,不同function使用传递数据
        const imgFile = {};
        var timer=null;
        var _this=null;
        function handleInputChange (event,flag) {
               _this=flag;
            const file = event.target.files[0];
            const imgMasSize = 1024 * 1024 * 10; // 10MB
            // 检查文件类型
            if(['jpeg', 'png', 'gif', 'jpg'].indexOf(file.type.split("/")[1]) < 0){
                // 自定义报错方式
                // Toast.error("文件类型仅支持 jpeg/png/gif!", 2000, undefined, false);
                $('.mask').html('文件只支持图片类型格式');
                $('.mask').removeClass('hide');
                timer=setTimeout(function(){
                    $('.mask').addClass('hide')
                },1800)
                return;
            }
            // 文件大小限制
            if(file.size > imgMasSize ) {
                // 文件大小自定义限制
                // Toast.error("文件大小不能超过10MB!", 2000, undefined, false);
                $('.mask').html('上传图片大小过大');
                $('.mask').removeClass('hide');
                timer=setTimeout(function(){
                    $('.mask').addClass('hide')
                },1800)
                return;
            }
            // 判断是否是ios
            if(!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
                // iOS
                transformFileToFormData(file);
                return;
            }
            // 图片压缩之旅
            transformFileToDataUrl(file);
        }
        // 将File append进 FormData
        function transformFileToFormData (file) {
            const formData = new FormData();
            // 自定义formData中的内容
            // type
            formData.append('type', file.type);
            // size
            formData.append('size', file.size || "image/jpeg");
            // name
            formData.append('name', file.name);
            // lastModifiedDate
            formData.append('lastModifiedDate', file.lastModifiedDate);
            // append 文件
            formData.append('file', file);
            // 上传图片
            uploadImg(formData);
        }
        // 将file转成dataUrl
        function transformFileToDataUrl (file) {
            const imgCompassMaxSize = 200 * 1024; // 超过 200k 就压缩
            // 存储文件相关信息
            imgFile.type = file.type || 'image/jpeg'; // 部分安卓出现获取不到type的情况
            imgFile.size = file.size;
            imgFile.name = file.name;
            imgFile.lastModifiedDate = file.lastModifiedDate;
            // 封装好的函数
            const reader = new FileReader();
            // file转dataUrl是个异步函数,要将代码写在回调里
            reader.onload = function(e) {
                const result = e.target.result;
                if(result.length < imgCompassMaxSize) {
                    compress(result, processData, false );    // 图片不压缩
                } else {
                    compress(result, processData);            // 图片压缩
                }
            };
            reader.readAsDataURL(file);
        }
        // 使用canvas绘制图片并压缩
        function compress (dataURL, callback, shouldCompress = true) {
            const img = new window.Image();
            img.src = dataURL;
            img.onload = function () {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                let compressedDataUrl;
                if(shouldCompress){
                    compressedDataUrl = canvas.toDataURL(imgFile.type, 0.2);
                } else {
                    compressedDataUrl = canvas.toDataURL(imgFile.type, 1);
                }
                callback(compressedDataUrl)
            }
        }
        function processData (dataURL) {
            // 这里使用二进制方式处理dataUrl
     
            const binaryString = window.atob(dataURL.split(',')[1]);
            const arrayBuffer = new ArrayBuffer(binaryString.length);
            const intArray = new Uint8Array(arrayBuffer);
            for (let i = 0, j = binaryString.length; i < j; i++) {
                intArray[i] = binaryString.charCodeAt(i);
            }
            const data = [intArray];
            let blob;
            try {
                blob = new Blob(data, { type: imgFile.type });
            } catch (error) {
                window.BlobBuilder = window.BlobBuilder ||
                    window.WebKitBlobBuilder ||
                    window.MozBlobBuilder ||
                    window.MSBlobBuilder;
                if (error.name === 'TypeError' && window.BlobBuilder){
                    const builder = new BlobBuilder();
                    builder.append(arrayBuffer);
                    blob = builder.getBlob(imgFile.type);
                } else {
                    throw new Error('版本过低,不支持上传图片');
                }
            }
    
            // blob 转file
            const fileOfBlob = new File([blob], imgFile.name);
            const formData = new FormData();
            // type
            formData.append('type', imgFile.type);
            // size
            formData.append('size', fileOfBlob.size);
            // name
            formData.append('name', imgFile.name);
            // lastModifiedDate
            formData.append('lastModifiedDate', imgFile.lastModifiedDate);
            // append 文件
            formData.append('image', fileOfBlob);
            console.log(formData.get('file'));
            console.log(formData.get('type'),33333333);
            uploadImg(formData);
        }
    
        // 上传图片
        function uploadImg (formData){   
            common.loadingShow();
            $.ajax({
                type:'post',
                url:"/edu/upload/uploadimg",
                data:formData,
                processData: false,
                contentType: false,
                cache: false,
                success:function (data) {
                    common.loadingHide()
                    console.log(data.msg)
                    $('.mask').html(data.msg);
                    $('.mask').removeClass('hide');
                    timer=setTimeout(function(){
                        $('.mask').addClass('hide')
                    },1800)
                    _this.attr('src',data.data.src)
                }
            })
    
    </script> 
    

    load.css

    
    /* loading */
    .gu_loading{ width:100%; height:100%; position:fixed; top:0; left:0;background: rgba(0,0,0,.2);display: flex;flex-direction: column; align-items: center;justify-content: center;}
    .gu_loading .loading_main{  transform:translate(-50%, -50%); -webkit-transform:translate(-50%, -50%); -moz-transform:translate(-50%, -50%); -ms-transform:translate(-50%, -50%); -o-transform:translate(-50%, -50%); background:rgba(0, 0, 0, 0.5); border-radius:.3125rem;margin-left: 160px;}
    .gu_loading .loading_main .close{ position:absolute; top:-0.40625rem; right:-0.40625rem; width:.546875rem; line-height:.546875rem; border:solid #000 .015625rem; border-radius:50%; text-align:center; color:rgba(0, 0, 0, 0.6);; font-size:.4375rem; }
    .gu_loading .loading_main .text{ width:100%; color:#fff; text-align:center; font-size:.28rem; margin:-20px 0 20px 0; padding:0 .15625rem; white-space:nowrap; text-overflow:ellipsis; overflow:hidden; }
    .gu_loading .loading_main .circle_bounce{ width:100px; height:85px; position:relative; }
    .gu_loading .loading_main .circle_bounce .child{ width:65%; height:65%; position:absolute; left:0;
        top: 10px;right: 0;margin: 0 auto; padding:.625rem; }
    .gu_loading .loading_main .circle_bounce .child:before{ content:''; display:block; margin:0 auto; width:15%; height:15%; background-color:#fff; border-radius:50%; -webkit-animation:circle_bounce_delay 1.2s infinite ease-in-out both; animation:circle_bounce_delay 1.2s infinite ease-in-out both; }
    .gu_loading .loading_main .circle_bounce .circle-2{ -webkit-transform:rotate(30deg); transform:rotate(30deg); }
    .gu_loading .loading_main .circle_bounce .circle-3{ -webkit-transform:rotate(60deg); transform:rotate(60deg); }
    .gu_loading .loading_main .circle_bounce .circle-4{ -webkit-transform:rotate(90deg); transform:rotate(90deg); }
    .gu_loading .loading_main .circle_bounce .circle-5{ -webkit-transform:rotate(120deg); transform:rotate(120deg); }
    .gu_loading .loading_main .circle_bounce .circle-6{ -webkit-transform:rotate(150deg); transform:rotate(150deg); }
    .gu_loading .loading_main .circle_bounce .circle-7{ -webkit-transform:rotate(180deg); transform:rotate(180deg); }
    .gu_loading .loading_main .circle_bounce .circle-8{ -webkit-transform:rotate(210deg); transform:rotate(210deg); }
    .gu_loading .loading_main .circle_bounce .circle-9{ -webkit-transform:rotate(240deg); transform:rotate(240deg); }
    .gu_loading .loading_main .circle_bounce .circle-10{ -webkit-transform:rotate(270deg); transform:rotate(270deg); }
    .gu_loading .loading_main .circle_bounce .circle-11{ -webkit-transform:rotate(300deg); transform:rotate(300deg); }
    .gu_loading .loading_main .circle_bounce .circle-12{ -webkit-transform:rotate(330deg); transform:rotate(330deg); }
    .gu_loading .loading_main .circle_bounce .circle-2:before{ -webkit-animation-delay:-1.1s; animation-delay:-1.1s; }
    .gu_loading .loading_main .circle_bounce .circle-3:before{ -webkit-animation-delay:-1s; animation-delay:-1s; }
    .gu_loading .loading_main .circle_bounce .circle-4:before{ -webkit-animation-delay:-0.9s; animation-delay:-0.9s; }
    .gu_loading .loading_main .circle_bounce .circle-5:before{ -webkit-animation-delay:-0.8s; animation-delay:-0.8s; }
    .gu_loading .loading_main .circle_bounce .circle-6:before{ -webkit-animation-delay:-0.7s; animation-delay:-0.7s; }
    .gu_loading .loading_main .circle_bounce .circle-7:before{ -webkit-animation-delay:-0.6s; animation-delay:-0.6s; }
    .gu_loading .loading_main .circle_bounce .circle-8:before{ -webkit-animation-delay:-0.5s; animation-delay:-0.5s; }
    .gu_loading .loading_main .circle_bounce .circle-9:before{ -webkit-animation-delay:-0.4s; animation-delay:-0.4s; }
    .gu_loading .loading_main .circle_bounce .circle-10:before{ -webkit-animation-delay:-0.3s; animation-delay:-0.3s; }
    .gu_loading .loading_main .circle_bounce .circle-11:before{ -webkit-animation-delay:-0.2s; animation-delay:-0.2s; }
    .gu_loading .loading_main .circle_bounce .circle-12:before{ -webkit-animation-delay:-0.1s; animation-delay:-0.1s; }
    @-webkit-keyframes circle_bounce_delay {
        0%, 80%, 100% {
        -webkit-transform: scale(0);
                transform: scale(0);
        }
        40% {
        -webkit-transform: scale(1);
                transform: scale(1);
        }
    }
    @keyframes circle_bounce_delay {
        0%, 80%, 100% {
        -webkit-transform: scale(0);
                transform: scale(0);
        }
        40% {
        -webkit-transform: scale(1);
                transform: scale(1);
        }
    }
    

    load.js

        loadingShow: function(par, callback) {
            par = par || {};
            par.hasClose = par.hasClose || false;
            par.title = par.title || "";
            par.title='加载中'
            callback = callback || function(){};
            var content = '<div class="gu_loading" style="z-index: 1000">'+
                            '<div class="loading_main">'+
                                '<div class="circle_bounce">'+
                                    '<div class="child circle-1"></div>'+
                                    '<div class="child circle-2"></div>'+
                                    '<div class="child circle-3"></div>'+
                                    '<div class="child circle-4"></div>'+
                                    '<div class="child circle-5"></div>'+
                                    '<div class="child circle-6"></div>'+
                                    '<div class="child circle-7"></div>'+
                                    '<div class="child circle-8"></div>'+
                                    '<div class="child circle-9"></div>'+
                                    '<div class="child circle-10"></div>'+
                                    '<div class="child circle-11"></div>'+
                                    '<div class="child circle-12"></div>'+
                                '</div>'+
                                '<div class="close">&times;</div>'+
                                '<div class="text">'+par.title+'</div>'+
                            '</div>'+
                        '</div>';
            $("body").append(content);
            if(par.title == ""){
                $(".gu_loading .text").remove();
            }
            if(!par.hasClose){
                $(".gu_loading .close").remove();
            }
            $(".gu_loading .close").click(function(){
                common.loadingHide();
                callback();
            });
        },
    
    
    
        loadingHide: function(){
            $(".gu_loading").remove();
        },
    
    }
    
    

    参考https://segmentfault.com/a/1190000010034177?utm_source=tag-newest

    相关文章

      网友评论

          本文标题:上传图片

          本文链接:https://www.haomeiwen.com/subject/ogyckctx.html