在vue中使用plupload上传图片到七牛(着重解决moxie is not defined问题)

       在传统的jquery或者原生JS环境下结合plupload上传到七牛的案例就不说了,一搜一大片,这里重点说说使用了vue之后,在vue环境下要保持相同的体验度上传图片到七牛,下面就是搞了接近两天摸索出来的,过程只想MMP,但是还是得到了满意的结果,算是功夫不负苦心人啊(这个过程真的是坑太多了)!

       这个排坑的过程就多说了,搞来搞去就是plupload和qiniu的js版本对不上的问题,然后就是各种变量找不到的问题,一部分是参考github上的解决办法解决的,一部分自己调试代码解决,经历不可说不痛苦,唉!

       着重说几点要注意的地方:

1.相对JS的引入,这里没有使用压缩之后的,直接使用的源码,因为要调试啊,不过有了webpack,也可以直接使用源码,因为最终是要打包的,无所谓引用什么,但建议还是引用源码,用了你就知道了:

//这里使用相对路径,就是该文件相对于static目录的路径
window.mOxie = window.moxie = require('../../../static/js/plupload/moxie')
require('../../../static/js/plupload/plupload.dev')
require('../../../static/js/qiniu/qiniu')

2.对应的plupload.dev.js:

注意看版本号:2.3.6,修改源码部分(括号里面的this改成window):

exports.plupload = plupload;

}(window, moxie));

}));

3.对应的qiniu.js,用的是目前的最新版,等下看js源文件就知道了,在源码里面要加下面这句代码:

mOxie.Env = mOxie.core.utils.Env;

4.最最坑的moxie.js,尼玛就是这个js搞了半天,在这个源码的最后面加上:

window.mOxie = exports.mOxie;

其他的就是使用部分了,还是贴一下,不然文章太短了,哈哈:

vue组件部分

<template>
    <!-- 图片上传组件 -->
    <div class="sg-upload-area" :id="uploadContainerId">
        <img :src="defaultImg" alt="" class="sg-upload-img" :id="uploadImgId" :style="imgButtonStype">
        <span class="sg-img-loading" v-if="ifShowLoading"></span>
        <span class="sg-img-progress-bar" v-show="ifShowBar">{{progress_percent}}</span>
    </div>
</template>

<script>
//这里使用相对路径,就是该文件相对于static目录的路径
window.mOxie = window.moxie = require('../../../static/js/plupload/moxie')
require('../../../static/js/plupload/plupload.dev')
require('../../../static/js/qiniu/qiniu')
export default {
    props:['imgButtonStype'],
    data() {
        return {
            defaultImg:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536823040797&di=656672375293c1e3f8c0719d90bdb2b2&imgtype=0&src=http%3A%2F%2Fwww.qqzhi.com%2Fuploadpic%2F2015-01-08%2F143039142.jpg',
            ifShowLoading:0,
            ifShowBar:0,//进度条显示隐藏
            progress_percent:"0%",
            img_cuid:new Date().getTime(),//图片唯一ID
            upload_area:0,
            upload_img:0,
            qiniu_domain:"https://img.senguo.cc/",//自己去修改,图床域名
            qiniu_token:"Pm0tzHLClI6iHqxdkCbwlSwHWZycbQoRFQwdqEI_:BmvYWOi-8S4u4ed7NEfiQ2YXS5E=:eyJkZWFkbGluZSI6MTUzNzM1MTEzMCwic2NvcGUiOiJzaG9waW1nIn0="
        };
    },
    mounted() {
        this.initUpload()
    },
    methods:{
        initUpload() {
            let _vue = this;
            let uploader = Qiniu.uploader({
                runtimes: 'html5,flash,html4',
                browse_button: _vue.upload_img,
                container: _vue.upload_area,
                max_file_size: '10mb',
                filters : {
                   // max_file_size : '4mb',//限制图片大小
                    mime_types: [
                        {title : "image type", extensions : "jpg,jpeg,png"}
                    ]
                },
                flash_swf_url: '../../../static/js/plupload/Moxie.swf',
                dragdrop: false,
                chunk_size: '4mb',
                domain: _vue.qiniu_domain,
                uptoken: _vue.qiniu_token,
                unique_names: false,
                save_key: false,
                auto_start: true,
                resize: {width: 800},
                init: {
                    'BeforeUpload':function(up, file){
                    },
                    'FilesAdded': function (up, files) {
                        var file = files[0];
                        !function(){
                            _vue.previewImage(file,function(imgsrc){
                                _vue.defaultImg = imgsrc;
                            });
                        }();
                        _vue.ifShowBar = 1;
                    },
                    'UploadProgress': function (up, file) {
                        console.log(file.percent)
                        _vue.progress_percent = file.percent+"%"
                    },
                    'FileUploaded': function (up, file, info) {
                        //$("#"+file.id).attr({"url":qiniu_domain+file.id+".jpg","src":qiniu_domain+file.id+".jpg"+"?imageView2/1/w/100/h/100"});
                        _vue.defaultImg = _vue.qiniu_domain+file.id+".jpg";
                    },
                    'Error': function (up, err, errTip) {
                        if (err.code == -600) {
                            alert("上传图片大小请不要超过4M");
                        } else if (err.code == -601) {
                            alert("上传图片格式只能为png、jpg图片");
                        } else if (err.code == -200) {
                            alert("当前页面过期,请刷新页面后再上传");
                        } else {
                            alert(err.code + ": " + err.message);
                        }
                        up.removeFile(err.file.id);
                    },
                    'Key': function (up, file) {
                        var key = file.id+".jpg";
                        return key;
                    }
                }
            });
        },
        /*转化图片为base64预览*/
        previewImage(file,callback) {//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
            if(!file || !/image\//.test(file.type)) return; //确保文件是图片
            if(file.type=='image/gif'){//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
                let fr = new moxie.image.Image();
                fr.onload = function(){
                    callback(fr.result);
                    fr.destroy();
                    fr = null;
                };
                fr.readAsDataURL(file.getSource());
            }else{
                let preloader = new moxie.image.Image();
                preloader.onload = function() {
                    preloader.downsize(100,100,true);//先压缩一下要预览的图片,宽,高
                    let imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',70) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
                    callback && callback(imgsrc); //callback传入的参数为预览图片的url
                    preloader.destroy();
                    preloader = null;
                };
                preloader.load( file.getSource() );
            }
        }
    },
    computed:{
        uploadImgId() {
            this.upload_img = "upload_img_"+this.img_cuid
            return this.upload_img
        },
        uploadContainerId() {
            this.upload_area = "upload_container_"+this.img_cuid
            return this.upload_area
        }
    }
};
</script>
<style lang="scss" scoped>
    .sg-upload-area{
        display: inline-block;
        position: relative;
        cursor: pointer;
        .sg-upload-img{
            display: inline-block;
            width: 60px;
            height: 60px;
        }
        .sg-img-loading{
            position: absolute;
            width:100%;
            height: 100%;
            z-index: 10;
        }
        .sg-img-progress-bar{
            position: absolute;
            left:0;
            bottom:0;
            width:100%;
            height: 14px;
            background-color: rgba(0, 0, 0, 0.6);
            color: #fff;
            font-size: 10px;
            line-height: 14px;
            text-align: center;
            z-index:10;
        }
    }
    
</style>

组件的使用(非常简单):

<template>
        <div>
			<upload-img imgButtonStype="width:100px;height:100px;"></upload-img>
	    </div>
</template>
<script> 
import UploadImg from '@/components/common/UploadImg'
export default {
    components:  {UploadImg},
    data() {
		return {
			
		}
	},
	methods: {

	},
	mounted() {

	}
}
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>

</style>

差不多就是这样了,我把我的static里面的文件打包一份,再传一下就ok了;

下载地址

猜你喜欢

转载自blog.csdn.net/playboyanta123/article/details/82745824
今日推荐