vue + elementUI 项目里使用qiniu插件实现上传图片功能

总结:按照七牛官网一步步来就可以实现。

官网链接:JavaScript SDK_SDK 下载_对象存储 - 七牛开发者中心

一、上传单张图片的配置和方法

具体实现步骤:

1、npm 安装qiniu依赖

npm install qiniu-js

2、npm 安装 plupload依赖

npm install plupload --save

3、在上传页面引入插件依赖

var qiniu = require('qiniu-js')

 

4、DOM部分:

<el-form-item label="上传图片:">
    <el-upload action="" :http-request="qiniuUploadCover" list-type="picture-card" :limit="2" :disabled="false" :auto-upload="true" :on-exceed="exceed"
                     :before-upload="beforeUpload" :on-remove="onRemove" :on-preview="handlePictureCardPreview" ref="addEditUpload" :file-list="fileList">
        <i class="el-icon-plus"></i>
     </el-upload>
     <el-dialog :visible.sync="showPic" size="tiny" :append-to-body="true">
         <img width="100%" :src="showPicUrl" alt="">
     </el-dialog>
     <span class="redFont" style="font-size:12px;">建议上传尺寸:宽750px 、高375px</span>
</el-form-item>

el-upload 的属性含义,具体可查看elementUI官网:

:limit="addEditDialog.limit"   

限制图片的数量

:before-upload="beforeUpload" 

上传前的钩子函数。一般对图片的格式、大小进行校验。

http-request="qiniuUpload"  

上传图片的钩子函数。点击upload控件、选中图片之后就会触发这个函数,在该函数里调七牛接口上传图片。

:on-exceed="exceed"

上传的图片数量超出限制时的钩子函数,一般弹出相关提示。

:disabled="false"   

禁用上传图片插件。

:on-remove="onRemove" 

移除图片的钩子函数。

:on-preview="handlePictureCardPreview" 

图片放大查看的钩子函数。

5、js部分:

beforeUpload() 

qiniuUploadCover()

getImagekey()

handlePictureCardPreview()

onRemove()

exceed()

/* 七牛插件公用的函数:
 * 图片上传前的钩子,对图片进行限制
 */
Vue.prototype.beforeUpload = function(file){
    //console.log(file);

     //const isJPG = file.type === 'image/jpeg' || 'image/jpg' || 'image/png';
     var isJPG;
     if(file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'){
        isJPG=true;
     }else{
        isJPG=false;
     }

     const isLt2M = file.size / 1024 / 1024 < 3;

     if (!isJPG) {
        //this.$message.error('上传头像图片只能是 jpeg/jpg/png 格式!');
        this.$message({
            message: '上传头像图片只能是 jpeg/jpg/png 格式!',
            type: 'error',
            duration:1500,
            showClose: true,
         });
      }
      if (!isLt2M) {
         //this.$message.error('上传头像图片大小不能超过 3MB!');
         this.$message({
             message: '上传头像图片大小不能超过 3MB!',
             type: 'error',
             duration:1500,
             showClose: true,
          });
       }
       return isJPG && isLt2M;
}

    /* 得到图片中间的key
     * 新增和编辑时上传图片到七牛都调用 _this.getImagekey(_this.oldPicUrl) 方法,参数要求:
     * 新增:_this.oldPicUrl=""
     * 编辑:_this.oldPicUrl 值为修改前的图片url
    */
    Vue.prototype.getImagekey = function(url){
        var key="tmp_bj_" + Date.parse(new Date());
        var count="0";
        if(url!=""){
            if(url.indexOf("http://image.qxdaojia.com")>=0){
                if(url.indexOf("?")>=0){
                    key=url.substring(26).substring(0,url.substring(26).lastIndexOf("?"));
                    count="1";//覆盖
                }else{
                    key=url.substring(26);
                    count="1";//覆盖
                }
            }
        }
        //其中覆盖时,key与url相等;普通上传时,url为空,key为上传的key.
        return { key:key , url : count == "0" ? "" : key };
    }
    //文件超出个数限制时的钩子
    Vue.prototype.exceed = function(files, fileList){
        // console.log(files);
        // console.log(fileList);
        this.$message({
            message: '上传的图片数量超出限制!',
            type: 'warning',
            duration:1500,
            showClose: true,
        });
    }

//移除upload控件的图片url
            onRemove (file, fileList) {
                // file : 当前被删除的图片
                // fileList : 删除后还剩下的图片
                //console.log(file);console.log(fileList);
                _this.oldPicUrl = file.url;//暂存被删掉的旧图片
                
                //删除一张图片之后的upload控件值
                var arr =[];
                fileList.forEach(function(ele){
                    arr.push(ele.url);
                })
                _this.form.rnImage=arr.toString();
            },
            handlePictureCardPreview(file) {//放大查看图片
                _this.showPicUrl = file.url;
                _this.showPic = true;
            },
            qiniuUploadCover(event){
                /* 新增和编辑时上传图片到七牛都调用此方法,参数要求:
                新增:paramObj:{key:"tmp_bj_" + Date.parse(new Date()),url:""}
                编辑:paramObj:_this.getImagekey(_this.oldPicUrl);
                */
               //console.log(_this.oldPicUrl);debugger
                var paramObj=_this.getImagekey(_this.oldPicUrl);
                uptokencover(paramObj).then(res => {
                    if(res.code==0){
                        var qiniu_token = res.data.uptoken;

                        /*  file: blob对象,上传的文件; 
                            key: string, 文件资源名
                            token: string, 上传验证信息,前端通过接口请求后端获得
                            putExtra: object, 
                            config: object
                        */
                        var putExtra={
                            fname: "",//文件原文件名
                            params: {},//用来放置自定义变量
                            mimeType: ["image/png", "image/jpeg", "image/gif"],//用来限定上传文件类型,指定null时自动判断文件类型。
                        }
                        var config={
                            useCdnDomain: true,//表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
                            region: qiniu.region.z2,//选择上传域名区域;当为 null 或 undefined 时,自动分析上传域名区域
                        }
                        var observable  = qiniu.upload(event.file, paramObj.key, qiniu_token, putExtra, config);
                        var subscription = observable.subscribe({
                            next(res){
                                // next: 接收上传进度信息,res 参数是一个带有 total 字段的 object,包含loaded、total、percent三个属性,提供上传进度信息。
                                //console.log(res);
                            },
                            error(err){
                                // 上传错误后触发,当不是 xhr 请求错误时,会把当前错误产生原因直接抛出,诸如 JSON 解析异常等;当产生 xhr 请求错误时,参数 err 为一个包含 code、message、isRequestError 三个属性的 object
                                //console.log(err);
                            }, 
                            complete(res){
                                //console.log(res);
                                // 接收上传完成后的后端返回信息,res 参数为一个 object, 为上传成功后后端返回的信息,具体返回结构取决于后端sdk的配置
                                //1、先把上传前的图片url保存为数组
                                var customaryImgArr = [];
                                if(_this.form.rnImage!=""){
                                    customaryImgArr = _this.form.rnImage.split(",");
                                }
                                //2、把当前上传的图片插入数组
                                customaryImgArr.push( "http://image.qxdaojia.com/"+paramObj.key+"?v="+Date.parse(new Date()) );
                                //3、把数组转换成string,给接口保存。
                                _this.form.rnImage = customaryImgArr.toString();
                                
                            }
                        }) // 上传开始
                    }else{
                        _this.$message({
                            message: res.message,
                            type: 'error',
                            duration:1500,
                            showClose: true,
                        });
                    }
                });
            },

二、上传多张图片的方法

1、Dom部分:给el-upload添加multiple属性,支持一次选择多图。

<el-upload :multiple="true"></el-upload>

2、【注意】上传图片时图片url要拼接唯一的key,通过_this.getImagekey(_this.oldPicUrl)来获取。但是同时上传多个文件时,短时间内多次调用_this.getImagekey()返回的key是相同的,所以此时需要在_this.getImagekey()返回的key后面再拼接唯一的字符标识。否则七牛上传图片会报614错误(文件已存在)。

其他的地方还是和上传单张图片时一样。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值