当前位置: 首页 > news >正文

文件上传到oss代码片段

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

import axios from '@/global/axios.js'

let expire = 0
let accessKeyId
let policy
let signature
let host
let callback

// 获取policy
function getPolicy (file, filePath, changeSize, callbackImg) {
    // 可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    let now = new Date().getTime() / 1000
    if (expire < now + 3) {
        axios.get('/api-oss/oss/policy')
            .then((result) => {
            let res = result.data
            if (res.code === 2000) {
            expire = res.data.expire
            accessKeyId = res.data.accessKeyId
            policy = res.data.policy
            signature = res.data.signature
            host = res.data.host
            callback = res.data.callback

            if (file.type.split('/')[0] === 'image') {
                imgChange(file, filePath, changeSize, callbackImg)
            } else {
                callbackOss(file, filePath, callbackImg)
            }
        }
    })
    } else {
        if (file.type.split('/')[0] === 'image') {
            imgChange(file, filePath, changeSize, callbackImg)
        } else {
            callbackOss(file, filePath, callbackImg)
        }
    }
}

// 上传文件到oss
function callbackOss (fileObj, filePath, callbackImg) {
    let formData = new FormData()
    formData.append('key', filePath)
    formData.append('policy', policy)
    formData.append('OSSAccessKeyId', accessKeyId)
    formData.append('success_action_status', '200') // 让服务端返回200,不然,默认会返回204
    formData.append('callback', callback)
    formData.append('signature', signature)
    formData.append('file', fileObj)

    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }
    axios.post(host, formData, config)
        .then(function (result) {
            uploadOss.imgPath = host + '/' + result.data.data.filename
            if (callbackImg) {
                callbackImg()
            }
        })
}

// 图片压缩函数
function imgChange (file, basePath, changeSize, callbackImg) {
    let changeSizeDefault = changeSize || '1'
    let reader = new FileReader()
    let img = new Image()
    reader.readAsDataURL(file)
    reader.onload = function (e) {
        img.src = e.target.result
    }
    let canvas = document.createElement('canvas')
    let context = canvas.getContext('2d')
    img.onload = function () {
        // 图片原生尺寸
        let originWidth = this.width
        let originHeight = this.height

        canvas.width = originWidth
        canvas.height = originHeight

        context.clearRect(0, 0, originWidth, originHeight)
        context.drawImage(img, 0, 0, originWidth, originHeight)
        canvas.toBlob(function (blob) {
            callbackOss(blob, basePath, callbackImg)
        }, file.type || 'image/png', changeSizeDefault)
    }
}

/**
 * 获取文件路径
 * @method getFilePath
 * @param {object} file 文件对象
 * @param {string} basePath 基础路径
 * @return {string} filePath 文件路径
 */
function getFilePath (file, basePath) {
    let filePath = ''
    let fileExtension = getBaseExtension(file.type)
    let filename = getUuid() + '.' + fileExtension
    let basePathRep = replace(basePath)
    if (basePathRep === '') {
        filePath = filename
    } else {
        filePath = basePathRep + '/' + filename
    }
    return filePath
}

// 获取文件扩展名
function getBaseExtension (fileType) {
    if (fileType === 'video/x-ms-wmv') {
        fileType = 'video/wmv' // 对wmv格式的视频文件进行处理
    }
    return fileType.split('/')[1]
}

/**
 * 生成36位 uuid
 * @returns {string} uuid
 */
function getUuid () {
    let s = []
    var hexDigits = '0123456789abcdefhijkmnprstwxyz'
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    return s.join('')
}

/**
 * 格式化
 * @param str 要格式化的字符串
 * @returns {string}
 */
function replace (str) {
    let replacedStr = str
    let length = replacedStr.length
    if (str.indexOf('/') === 0) {
        if (length === 1) {
            replacedStr = ''
        } else {
            replacedStr = str.substring(1, length)
        }
        length -= 1
    }
    if (length - 1 === replacedStr.lastIndexOf('/')) {
        replacedStr = replacedStr.substring(0, length - 1)
    }
    return replacedStr
}

// 对外接口对象封装
let uploadOss = {
    imgPath: '',
    // file文件上传
    fileInit: function (file, basePath, changeSize, callbackImg) {
        let filePath = getFilePath(file, basePath)
        getPolicy(file, filePath, changeSize, callbackImg)
    }
}

export default uploadOss

转载于:https://my.oschina.net/u/2306318/blog/1624140

相关文章:

  • Idea卡在Maven导入工程
  • 学习笔记 - Git
  • forget word out a~2
  • SSM-MyBatis-18:Mybatis中二级缓存和第三方Ehcache配置
  • 34.CSS传统布局【上】
  • 测试同学难道要写一辈子的hello world?
  • 扒一扒AR增强现实技术的专利态势
  • oracle em 5500访问问题
  • 笔记 OSPF多区域配置 STUB区域 路由重分发 NSSA区域配置
  • apache+tomcat配置负载均衡,实现http与websocket接口分压
  • C 语言整型谜题
  • React Router v4 学习笔记
  • Django--middleware 详解
  • AI降临——“人工智能女王”卡塞尔中国行
  • 内核解密 | Oracle 18c 数据库安装ORA-12754的两种解决方案
  • 2019.2.20 c++ 知识梳理
  • happypack两次报错的问题
  • HTML5新特性总结
  • Javascript设计模式学习之Observer(观察者)模式
  • JS 面试题总结
  • Laravel5.4 Queues队列学习
  • Linux各目录及每个目录的详细介绍
  • Perseus-BERT——业内性能极致优化的BERT训练方案
  • PHP变量
  • Python 基础起步 (十) 什么叫函数?
  • python学习笔记 - ThreadLocal
  • React as a UI Runtime(五、列表)
  • Vue小说阅读器(仿追书神器)
  • - 概述 - 《设计模式(极简c++版)》
  • 码农张的Bug人生 - 见面之礼
  • 全栈开发——Linux
  • 一起来学SpringBoot | 第十篇:使用Spring Cache集成Redis
  • ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
  • #pragma once
  • $(function(){})与(function($){....})(jQuery)的区别
  • (webRTC、RecordRTC):navigator.mediaDevices undefined
  • (二) Windows 下 Sublime Text 3 安装离线插件 Anaconda
  • (附源码)node.js知识分享网站 毕业设计 202038
  • (附源码)ssm高校升本考试管理系统 毕业设计 201631
  • (附源码)计算机毕业设计SSM疫情居家隔离服务系统
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (考研湖科大教书匠计算机网络)第一章概述-第五节1:计算机网络体系结构之分层思想和举例
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (幽默漫画)有个程序员老公,是怎样的体验?
  • .cn根服务器被攻击之后
  • .L0CK3D来袭:如何保护您的数据免受致命攻击
  • .NET Core/Framework 创建委托以大幅度提高反射调用的性能
  • .NET 设计模式—适配器模式(Adapter Pattern)
  • .NETCORE 开发登录接口MFA谷歌多因子身份验证
  • /etc/motd and /etc/issue
  • @Query中countQuery的介绍
  • @vue/cli 3.x+引入jQuery
  • [ solr入门 ] - 利用solrJ进行检索
  • [8-27]正则表达式、扩展表达式以及相关实战
  • [android] 天气app布局练习