zoukankan      html  css  js  c++  java
  • VUE集成Cos腾讯图片服务器

    安装 npm install --save cos-js-sdk-v5   spark-md5

    <el-upload
    class="upload-demo"
    :file-list="newImages"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleAvatarSuccess"
    :before-remove="beforeRemove"
    :before-upload="beforeAvatarUpload">
    <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    import uploadFile from '../../util/uploadFile'
    const bannerOptions = [{
    type: 'image/jpeg',
    size: 10
    }, {
    type: 'image/png',
    size: 10
    }]
    beforeAvatarUpload (file) {
    let that = this
    // console.log('before',that.imgList)
    // 显示loading动画
    this.imgUpdateImg = true
    let isJPG = false
    let isLt2M = false
    let fileSize = 0
    for (let option of bannerOptions) {
    if (option.type === file.type) {
    isJPG = true
    fileSize = option.size
    if (option.size > file.size / 1024 / 1024) {
    isLt2M = true
    }
    }
    }
    if (!isJPG) {
    that.$message.error('上传的图片只能是 jpg/png 格式')
    that.imgUpdateImg = false
    }
    if (!isLt2M) {
    that.$message.error('上传文件的大小不能超过 ' + fileSize + 'MB!')
    that.imgUpdateImg = false
    }
    this.selectFile(file)
    return isJPG && isLt2M
    },

    selectFile (event) {
    console.log(event)
    // console.log('selectFile', event.target.files[0].name)
    // 调用上传方法,传入选择的文件对象
    // this.uploadFile(event.target.files[0], () => {
    // console.log('ckckckckckckckckckckk')
    // })
    // console.log('selectFile', event.target.files[0])
    uploadFile(event, (key) => {
    console.log(key)
    this.newImages.push(key)
    console.log(this.newImages)
    })
    uploadFile.js 文件

    import Vue from 'vue'
    import SparkMD5 from 'spark-md5'
    import { cosConfig } from './config'
    import COS from 'cos-js-sdk-v5'

    export default function(file,backtopage) {
    var key = ''
    Vue.prototype.uploadFile = uploadFile
    console.log('hhhhhhhhhhhhhhhhhhhhhhhhh')
    console.log(cosConfig)
    var cos = new COS({
    getAuthorization: function (params, callback) {//获取签名 必填参数
    // 方法二(适用于前端调试)
    var authorization = COS.getAuthorization({
    SecretId: cosConfig.SecretId,
    SecretKey: cosConfig.SecretKey,
    Method: params.Method,
    Key: params.Key
    });
    callback(authorization);
    }
    });
    console.log(cos)
    uploadFile(file, backtopage)
    // 将上传文件的方法挂载到vue的原型链上面
    // Vue.prototype.uploadFile = uploadFile

    var requestCallback = function (err, data) {
    console.log(err || data);
    if (err && err.error) {
    console.log(key)
    // wx.showModal({ title: '返回错误', content: '请求失败:' + err.error.Message + ';状态码:' + err.statusCode, showCancel: false });
    } else if (err) {
    console.log(key)
    // wx.showModal({ title: '请求出错', content: '请求出错:' + err + ';状态码:' + err.statusCode, showCancel: false });
    } else {
    console.log(key)
    backtopage(key)
    // wx.showToast({ title: '上传成功', icon: 'success', duration: 3000 });
    }
    };

    function uploadFile (file, backtopage) {
    console.log('nnnnnnnnnnnnnnnnnnn')
    console.log(file)
    // 得到md5码
    getFileMD5(file, md5 => {
    console.log(file)
    // 存储文件的md5码
    file.md5 = md5
    console.log(file.md5)
    let subfix = file.name.substr(file.name.lastIndexOf('.'))
    key = file.md5 + subfix
    console.log(key)
    cos.headObject({
    Bucket: cosConfig.Bucket, /* 必须 */
    Region: cosConfig.Region, /* 必须 */
    Key: key, /* 必须 */
    }, function (err, data) {
    if (err != null) {
    console.log('wrong')
    console.log(err)
    cos.putObject({
    Bucket: cosConfig.Bucket,
    Region: cosConfig.Region,
    Key: key,
    Body: file,
    onProgress: function (info) {
    console.log(JSON.stringify(info));
    }
    }, requestCallback)
    } else if (data != null) {
    backtopage(key)
    }
    });
    })
    }

    // 获得文件md5
    function getFileMD5(file, callback) {
    //声明必要的变量
    var fileReader = new FileReader(),

    //文件每块分割2M,计算分割详情
    chunkSize = 2097152,
    chunks = Math.ceil(file.size / chunkSize),
    currentChunk = 0,

    //创建md5对象(基于SparkMD5)
    spark = new SparkMD5()

    //每块文件读取完毕之后的处理
    fileReader.onload = function(e) {
    //每块交由sparkMD5进行计算
    spark.appendBinary(e.target.result)
    currentChunk++

    //如果文件处理完成计算MD5,如果还有分片继续处理
    if (currentChunk < chunks) {
    loadNext()
    } else {
    callback(spark.end())
    }
    }

    //处理单片文件的上传
    function loadNext() {
    var start = currentChunk * chunkSize,
    end = start + chunkSize >= file.size ? file.size : start + chunkSize

    fileReader.readAsBinaryString(file.slice(start, end))
    }

    loadNext()

    }

    }


  • 相关阅读:
    java后台生成图片二维码
    layui框架下的摸索与学习
    eclipse/myeclipse中js/java的自动提示只有4个字符怎么解决
    Git日常操作指令
    node指南开发练习笔记(1)-- express
    echart全国主要城市某数据的显示
    微信公众号开发获取当前位置
    显示上传图片
    移动端Safari onclick事件兼容
    Plupload上传插件自定义图片的修改
  • 原文地址:https://www.cnblogs.com/laixin09/p/10064786.html
Copyright © 2011-2022 走看看