vue upload 视频上传 七牛云存储

一、上传到后端指定的服务器 

        后端人员有配置好服务器地址,我们可以直接用element-ui的组件进行视频上传,直接将el-upload组件的action属性配置成后端给的地址即可。

一篇比较好的参考文章,细看


1.引入库

element官网引入库配置

npm i element-ui -S

2.配置上传组件参数(具体参考el-upload组件)

    如选取可拖拽/点击上传视频的组件:

<el-upload
  class="upload-demo"
  drag                                                // 可拖拽上传
  action="https://jsonplaceholder.typicode.com/posts/"   // 上传地址,后端给(没有则填"#")
  multiple                                            // 可同时上传多个文件
  :show-file-list="false"                             // 去除默认上传时展示的进度条
  :before-upload="beforeUpload"                       // 配置上传文件前的格式校验规则
  accept=".mp4"                  // 配置文件夹点开后,过滤展示的文件格式(字符串类型)
>
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>

methods:{
    beforeUpload(file){
        if ( file.name.split('.')[1].toLowerCase() != 'mp4' ){
            this.$message.error('文件格式错误~')
            return false;   // 终止上传
        }

    }
}

 二、上传到七牛云

1、引入库

JavaScript SDK 下载_对象存储 (官网)

上传视频到七牛云并获取封面  (参考文章)

npm install qiniu-js

import * as qiniu from 'qiniu-js'

2、实现方式

(1)配置上传参数示例(参考上面的官网)

// 上传视频至七牛云
uploadVideo(file){
     const suffix = file.name.split('.')[1];  // 后缀名
     const _this = this;
     const current = new Date().getTime();
     // const key = `video_${current}.${suffix}`;    // key为上传后文件名 必填
     const key = null;    // key:文件资源名,为空字符串时则文件资源名也为空,为 null 或者 undefined 时则自动使用文件的 hash 作为文件名
     const config = {
           useCdnDomain: true,
           region: qiniu.region.z2,    // 根据地区不同,官网有不同的配置
           concurrentRequestLimit: 1000,
     };
     var observable = qiniu.upload(file, key, _this.qiniuToken, config);  // _this.qiniuToken 由后端提供,通过接口获取
     var observer = {
         next(res) {    // 用于展示上传进度
             _this.percent = res.total.percent;
         },
         error(err) { 
             _this.$Message.destroy();
             _this.$Message.error(err.data.error);  // 上传错误报错
         },
         // 上传成功的回调,res中可以拿到七牛云返回的key和hash
         complete(res) {
             _this.videoForm.file = res.hash;  // 七牛云回传的视频hash 和 key
             _this.$Message.destroy();
             _this.$Message.success('上传成功!');
             if ( !_this.videoForm.cover ) _this.getVideoCover(file);   // 默认截取视频第一帧作为封面(存在用户自定义上传的封面时,不进行覆盖)
                 let videoName = file.name.split('.')[0].length <= 30 ?  file.name.split('.')[0] : file.name.split('.')[0].substring(0,30);
                 _this.videoForm.title = _this.videoForm.title || videoName;  // 默认将视频名称作为标题
         },
     };
     this.subscription = observable.subscribe(observer);  // 开始上传(赋值给一个全局的参数,可以在合适的时机通过:subscription.unsubscribe() 终止上传)
 },

参数说明: (参考上述官网中的 API Reference Interface

        observer: observer 为一个 object,用来设置上传过程的监听函数,有三个属性 next、error、complete:

const observer = {
  next(res){
    // 接收上传进度信息的回调函数
  },
  error(err){
    // 上传错误后触发
  },
  complete(res){
    // 接收上传完成后的后端返回信息,具体返回结构取决于后端 SDK 的配置,笔者配置后返回的是每一个上传资源对应唯一的key和hash值,可以用该值拼接上后端配置的头部,对该资源进行网络请求。
  }
}

(2)拿到上传到七牛云的图片路径:图片上传到七牛云后,根据后端返回的注册配置地址+七牛云返回的图片/视频唯一的key值,组合成互联网上图片/视频的访问路径。

如: 

3、完整代码

<template>
    <el-upload
        class="upload-box"
        ref="upload"
        :show-file-list="false"
        :before-upload="beforeUpload"
        accept=".mp4"
        :disabled="disableUpload"
        :max-size="1024 * 1024"
        action="#"     
    >
       <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<script>
export defalt{
    methods:{
        beforeUpload(file){
            if ( file.name.split('.')[1].toLowerCase() != 'mp4'){
                this.errorMessage = '文件格式错误,只允许后缀名为.mp4的文件';
                return false;  // 终止上传
             } else {
                this.uploadVideo(file);  // 上传视频到七牛云
             }
        },
        uploadVideo(file){    // 为上述示例函数
            // ...
        }
    }
} 
</script>

提示:由于上传到七牛云,而非后端配置的服务器地址,所以el-upload中的 action = “#” 


拓展:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答你的问题。为了在ElementUIUpload中使用七牛云储存图片,你需要进行以下步骤: 1. 首先,你需要在七牛云上创建一个存储空间,并获取到你的Access Key和Secret Key。 2. 然后,在你的Vue项目中安装七牛云的SDK,可以使用npm命令进行安装: ``` npm install qiniu-js --save ``` 3. 在你的Vue组件中,你需要引入ElementUIUpload组件,并添加一个自定义的上传方法。这个方法将会在文件上传时被调用: ```javascript <template> <el-upload class="upload-demo" action="/upload" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :headers="headers" :data="data" :file-list="fileList" multiple> <el-button size="small" type="primary">点击上传</el-button> </el-upload> </template> <script> import { Upload } from 'element-ui'; import Qiniu from 'qiniu-js'; export default { components: { Upload }, data() { return { fileList: [], token: '', key: '', domain: 'http://xxx.xxx.xxx.xxx/', headers: { 'Authorization': '', 'x-qiniu-url': '' }, data: { token: '', key: '' } }; }, methods: { beforeUpload(file) { // 获取上传凭证 let that = this; return new Promise((resolve, reject) => { axios.get('YOUR_UPLOAD_URL') .then(response => { that.token = response.data.token; that.key = response.data.key; that.headers.Authorization = `UpToken ${that.token}`; that.headers['x-qiniu-url'] = that.domain; that.data.token = that.token; that.data.key = that.key; resolve(); }) .catch(error => { reject(error); }) }); }, handleSuccess(response, file, fileList) { // 上传成功回调 console.log(response); }, handleError(error, file, fileList) { // 上传失败回调 console.log(error); } } } </script> ``` 在这段代码中,我们引入了ElementUIUpload组件和七牛云的SDK,然后在data中定义了一些变量,包括上传凭证、上传文件的key、七牛的域名、请求头和请求参数等。在beforeUpload方法中,我们向你的服务器请求上传凭证,在请求成功后将认证信息和请求参数赋值给data和headers变量。在handleSuccess和handleError方法中,我们可以处理上传成功和上传失败的情况。 4. 最后,你需要在你的服务器端实现上传凭证的生成。可以使用七牛云的SDK,也可以使用其他语言的SDK,例如Java或Python。在服务器端生成上传凭证后,将凭证和上传文件的key返回给前端。 例如,在Node.js中,你可以使用qiniu-sdk: ```javascript const qiniu = require('qiniu'); const accessKey = 'YOUR_ACCESS_KEY'; const secretKey = 'YOUR_SECRET_KEY'; const bucket = 'YOUR_BUCKET_NAME'; const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); const options = { scope: bucket, expires: 7200 }; const putPolicy = new qiniu.rs.PutPolicy(options); const uploadToken = putPolicy.uploadToken(mac); app.get('/uploadToken', (req, res) => { const key = req.query.filename; res.json({ token: uploadToken, key: key }); }); ``` 在这个例子中,我们使用qiniu-sdk生成上传凭证,并在/uploadToken路由中返回凭证和上传文件的key。 这样,你就可以在ElementUIUpload中使用七牛云存储图片了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值