Vue element-ui 上传至oss

  1. 下载 ali-oss
npm install ali-oss
  1. 封装oss上传工具 新建ali-oss.js
import http from './request' //接口请求封装

let OSS = require('ali-oss');

/**
 *  [region] {String}:bucket所在的区域, 默认oss-cn-hangzhou。
 *  [accessKeyId] {String}:通过阿里云控制台创建的AccessKey。
 *  [accessKeySecret] {String}:通过阿里云控制台创建的AccessSecret。
 *  [bucket] {String}:通过控制台或PutBucket创建的bucket。
 */
function ikjOss() {}

ikjOss.prototype.client = function (func) {
    //请求后台获取秘钥
    http.post('/oss', '').then(res => {
        let client = new OSS({
            region: res.data.region,
            accessKeyId: res.data.accessKeyId,
            accessKeySecret: res.data.accessKeySecret,
            bucket: res.data.bucket
        });
        func(client);
    }).catch(error => {
        console.log('秘钥获取失败')
    })
};

const ikj_oss = new ikjOss()

export default ikj_oss
  1. vue使用
<template>
    <div class="oss">
        <el-upload :before-remove="beforeRemove"
                   :before-upload="beforeAvatarUpload"
                   :file-list="fileList"
                   :http-request="upload"
                   :limit="limit"
                   :on-exceed="handleExceed"
                   :on-remove="handleRemove"
                   :on-success="handleSuccess"
                   action
                   class="upload-demo">
            <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <el-progress :percentage="progress"
                     :stroke-width="15"
                     :text-inside="true"
                     v-show="showProgress">
        </el-progress>
    </div>
</template>

<script>
    export default {
        name: 'oss',
        data() {
            return {
                fileList: [],//文件列
                limit: 1, //最大上传文件数
                showProgress: false,//进度条的显示
                progress: 0 //进度条数据
            };
        },
        methods: {
            // 文件超出个数限制时的钩子
            handleExceed(files, fileList) {
                this.$message.warning(`每次只能上传 ${this.limit} 个文件`);
            },
            // 删除文件之前的钩子
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}?`);
            },
            // 文件列表移除文件时的钩子
            handleRemove(file, fileList) {
                this.$emit('on-remove', file, fileList)
            },
            // 文件上传成功时的钩子
            handleSuccess(response, file, fileList) {
                this.fileList = fileList;
            },
            //文件上传前的校验
            beforeAvatarUpload(file) {
                const isLt100M =
                    file.size / 1024 / 1024 > 0 && file.size / 1024 / 1024 < 1024;
                const isLt30 = file.name.length < 30;
                if (file.type !== 'image/png') {
                    this.$message.error("请上传PNG格式图片");
                    return false;
                }
                if (!isLt100M) {
                    this.$message.error("上传大小要在0MB~1GB之间哦!");
                    return false;
                }
                if (!isLt30) {
                    this.$message.error("上文件名称长度必须要小于30个文字哦!");
                    return false;
                }
            },
            //覆盖默认的上传行为,自定义上传的实现
            upload(file) {
                const that = this;
                that.$oss.client(function (client) {
                    //client.multipartUpload('文件路径/文件名称','上传文件')
                    client.multipartUpload(`zsx/zsx`, file.file, {
                        progress: function (p) {
                            //p进度条的值
                            that.showProgress = true;
                            that.progress = Math.floor(p * 100);
                        }
                    }).then(result => {
                        //上传成功返回值,可针对项目需求写其他逻辑
                        that.$message({
                            message: '文件上传成功',
                            type: 'success'
                        });
                        console.log(result);
                    }).catch(err => {
                        that.$message.error('上传失败,请重试。');
                        console.log("err:", err);
                    });
                })
            }
        }
    }
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • UI组件 element- 饿了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的组件库 m...
    小姜先森o0O阅读 13,281评论 0 72
  • UI组件 element- 饿了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的组件库 m...
    柴东啊阅读 15,895评论 2 140
  • 基于Vue的一些资料 内容 UI组件 开发框架 实用库 服务端 辅助工具 应用实例 Demo示例 element★...
    尝了又尝阅读 4,868评论 0 1
  • 时间终于走到这一天,当班主任老师一遍遍地在微信群里发布各种注意事项时,我的心还是被一次次吊起,莫名的紧张感让我有点...
    苇絮轻扬阅读 1,404评论 0 2
  • (庐山恋) 文/菊 庐山五岭苍松劲, 独秀云峰插碧空; 奇幻容颜均不现, 只缘身处雾溟中。 【平水韵】一东 (丙申...
    斌之志阅读 3,480评论 19 22