七牛上传

 

HTML中:

js中:

// 引入七牛的js
import * as qiniu from 'qiniu-js'
//定义变量
data: {
        dialogVisible: false, //弹出框隐藏
        token: "", //获取到的七牛token
        file: "", //选择要上传的文件
        pathPrex: "xxxxx/", //七牛存储控制默认url前缀
        key: "", //上传成功之后返回的图片后缀

        addForm: {
            dialogImageUrl: []
        }
}
mounted() {
        this._initToken();
}
//定义方法

methods: {
            // 图片上传函数开始
        _initToken() {  //获取七牛所需的token
            let ctx = this;
            $.ajax({
                type: 'GET',
                url: /*后端地址*/,
                headers: {
                    
                },
                success: function (data) {
                    console.log(data);
                    if(data.ret == 0){
                        ctx.token = data.model.token;
                    }
                },
                error: function (data) {
                    console.log(data)
                }
            })
        },
        delUploadImg: function (index) { //删除当前下标的图片
            this.addForm.dialogImageUrl.splice(index,1);
        },
        handleAddImg: function() {  //显示弹出框
            this.dialogVisible = true;
        },
        openFile: function () {   //间接点击上传图片按钮
            this.$refs.qiniuUpload.click();
        },
        dealKey() {  //获取当前的年月 保证图片的唯一性
            let year = new Date().getFullYear();
            let month = new Date().getMonth();
            return `${year}/${month}`;
        },
        uploadInputchange: function () {  //图片上传至七牛 相关配置
            let ctx = this;
            this.file = this.$refs.qiniuUpload.files[0];
            let file = this.file;
            // console.log(file);
            let uploadToken = this.token;
            let qnConfig = {
                useCdnDomain: true,
                region: null
            };
            let key = `${this.dealKey()}/${Math.floor(Math.random() * 999999)}/${file.name}`;
            let putExtra = {
                fname: file.name.split(".")[0], //文件原文件名
                params: {}, //用来放置自定义变量
                mimeType: null
            };
            let observer = {
                next: function(res) {},
                error: function(err) {},
                complete: function(res) {
                    ctx.key = res.key;
                    let newImg = `${ctx.pathPrex}${res.key}`;
                    ctx.addForm.dialogImageUrl.push(newImg);
                    ctx.dialogVisible = false;
                }
            };
            let observable = qiniu.upload(file, key, uploadToken, putExtra, qnConfig);
            let subscription = observable.subscribe(observer); // 上传开始
        },
        // 图片上传函数结束
}

 

你可能感兴趣的:(七牛上传)