vue antd envia vídeos ou fotos para o Alibaba Cloud oss

vue antd envia vídeos ou fotos para o Alibaba Cloud oss

1. Meio Ambiente

Precisa ser apresentado com antecedência

npm install ali-oss

npm i moment

2. Encapsular cilent

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


export function client(obj) {
    
    

 let tamp = {
    
    

  region: obj.region || "xxxxxxx",

  accessKeyId: obj.accessKeyId || "xxxxxxxx", 

  accessKeySecret: obj.accessKeySecret || "xxxx", 

  bucket: obj.bucket || "xxxxxxx",

  secure: true,   // secure: 配合region使用,如果指定了secure为true,则使用HTTPS访问 

 }

 var client = new OSS(tamp)  

 return client

}

3. Encapsular um componente antd para upload de arquivos

O código está na parte inferior

Primeiro, você precisa de um componente a-upload para fazer upload de arquivos, uma barra de progresso, detectar o tipo de arquivo em beforeUpload e fazer upload do arquivo para o Alibaba Cloud OS em customRequest.

1.beforeUpload determina o tipo de arquivo

beforeUpload(file) {
    
    
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/svg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/gif' ||
    file.type === 'video/ogg' ||
    file.type === 'video/flv' ||
    file.type === 'video/avi' ||
    file.type === 'video/wmv' ||
    file.type === 'video/mov' ||
    file.type === 'video/mp4'
  if (!isJpgOrPng) {
    
    
    this.$message.error('只能上传图片/视频!')
    return
  }
},

2. arquivo de upload customRequest

1. Prefixo do arquivo

Coloque o tipo de arquivo primeiro

  if (file.type === 'video/ogg' ||
    file.type === 'video/flv' ||
    file.type === 'video/avi' ||
    file.type === 'video/wmv' ||
    file.type === 'video/mov' ||
    file.type === 'video/mp4') {
    
    
    fileType = 'videos/'
  } else {
    
    
    fileType = 'images/'
  }

ano mês dia

  let time1 = moment().format('YYYY') // 年
  let time2 = moment().format('MM') // 月
  let time3 = moment().format('DD') // 日

O file.uid e o nome do arquivo ao fazer upload de arquivos podem obter um gerenciamento ordenado de imagens.

Tipo de arquivo + ano/mês/dia como diretório

arquivoDir + arquivo.uid + arquivo.nome

2. Upload unificado de várias partes

Como o vídeo precisa ser carregado em partes, ele é unificado em multipart uploads.

client(tamp) cria instância oss, multipartUpload multipart upload

progress monitora a barra de progresso e a arredonda,

Quando bem-sucedido, o caminho carregado em oss e o tipo de arquivo são retornados.

  client(tamp).multipartUpload(fileDir + file.uid + file.name, file, {
    
    
    progress: function (p) {
    
    
      const e = {
    
    };
      e.percent = Math.floor(p * 100);
      _this.defaultPercent = e.percent
    }
  }
  ).then(res => {
    
    
    _this.$emit('url', res.res.requestUrls[0].split("?")[0], file.type)
  }).catch(err => {
    
    
    this.$emit('btnStartLoading', false)
    _this.$message.error('上传失败,请检查上传文件或是否配置了云存储服务器')
  }).finally(() => {
    
    
    this.showProgress = false
  })

Tratamento de $ emit

Existem requisitos de código específicos aqui. Por favor, me dê algumas idéias.

    getimgurl(e, type) {
    
    
      let arr = ['video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov', 'video/mp4']
      if (arr.indexOf(type) !== -1) {
    
    
        this.fileArr.push({
    
    
          mp4: e,
          explain: ''
        })
        this.btnLoading = false
      } else {
    
    
        this.fileArr.push({
    
    
          img: e,
          explain: ''
        })
        this.btnLoading = false
      }
    }

Capa do vídeo

t unidade de tempo da captura de tela ms, [0, duração do vídeo]
w largura da captura de tela, se especificado como 0, o valor do pixel é calculado automaticamente: [0, largura do vídeo]
h altura da captura de tela, se especificado como 0, calculado automaticamente, se w e h são ambos 0, a saída é o valor de pixel de largura e altura do vídeo original: [0, altura do vídeo]
m modo de captura de tela, se não for especificado, é o modo padrão e a captura de tela é baseada com precisão no tempo. Se rápido for especificado, o quadro-chave mais recente antes do ponto no tempo será capturado.Valor de enumeração: rápido
f Valor de enumeração do formato da imagem de saída: jpg, png

Emendando atrás do caminho do vídeo?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast

código

// uploadImg_AvI/index.vue

<template>
  <div class="clearfix">
    <!-- 自定义上传事件customRequest -->
    <a-upload ref="upload" :customRequest="customRequest" :beforeUpload="beforeUpload" class="upload-list-inline"
      :showUploadList="false">
      <a-button>
        <a-icon type="upload" />上传图片/视频
      </a-button>
      <!-- 进度条 -->
      <a-progress v-if="showProgress" :percent="defaultPercent" />
    </a-upload>
  </div>
</template>
<script>
import {
    
     client } from "@/utils/alioss"
import moment from 'moment'
export default {
    
    
  data() {
    
    
    name: 'uploadMp4'
    return {
    
    
      previewVisible: false,
      previewImage: '',
      fileList: [],
      defaultPercent: 0,
      showProgress: false,
    }
  },
  methods: {
    
    
    customRequest(options) {
    
    
      let file = options.file
      let fileType = ''
      // 这一步有些重复,可以在beforeUpload 实现
      if (file.type === 'video/ogg' ||
        file.type === 'video/flv' ||
        file.type === 'video/avi' ||
        file.type === 'video/wmv' ||
        file.type === 'video/mov' ||
        file.type === 'video/mp4') {
    
    
        fileType = 'videos/'
      } else {
    
    
        fileType = 'images/'
      }
      this.showProgress = true
      let _this = this
      console.log(options);
      this.$emit('btnStartLoading', true)
      let tamp = {
    
    }
      // 由于我的系统中有多个oss 所以需要按需配置
      this.$store.state.user.info.schools.forEach(val => {
    
    
        // oss_type 是否为系统的
        val.oss_domain = val.oss_domain.replace(/\..*$/, '')
        if (val.id == this.$store.state.user.school) {
    
    
          tamp['region'] = val.oss_domain || undefined
          tamp['accessKeyId'] = val.access_key || undefined
          tamp['accessKeySecret'] = val.access_secret || undefined
          tamp['bucket'] = val.bucket || undefined
          tamp['oss_type'] = val.oss_type == 1 ? true : false
        }
      })

      let time1 = moment().format('YYYY') // 年
      let time2 = moment().format('DD') // 月
      let time3 = moment().format('hh') // 日
      let fileDir = fileType + this.$store.state.user.school + '/' + time1 + '/' + time2 + '/' + time3 + '/'
      client(tamp).multipartUpload(fileDir + file.uid + file.name, file, {
    
    
        progress: function (p) {
    
    
          const e = {
    
    };
          e.percent = Math.floor(p * 100);
          _this.defaultPercent = e.percent
        }
      }
      ).then(res => {
    
    
        _this.$emit('url', res.res.requestUrls[0].split("?")[0], file.type)
      }).catch(err => {
    
    
        this.$emit('btnStartLoading', false)
        _this.$message.error('上传失败,请检查上传文件或是否配置了云存储服务器')
      }).finally(() => {
    
    
        this.showProgress = false
      })
    },
    beforeUpload(file) {
    
    
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/svg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif' ||
        file.type === 'video/ogg' ||
        file.type === 'video/flv' ||
        file.type === 'video/avi' ||
        file.type === 'video/wmv' ||
        file.type === 'video/mov' ||
        file.type === 'video/mp4'
      if (!isJpgOrPng) {
    
    
        this.$message.error('只能上传图片/视频!')
        return
      }
    },
    handleCancel() {
    
    
      this.previewVisible = false
    }
  }
}
</script>

Cruze domínios e configure o Alibaba Cloud oss

Se você não configurou vários domínios ou gerou informações de configuração, será necessário configurá-los.

(31 mensagens) Vue transfere fotos diretamente para Alibaba Cloud OSS (upload direto único)_vue Alibaba Cloud transferência direta__Blog de Xiao Zheng - Blog CSDN

Acho que você gosta

Origin blog.csdn.net/lfeishumomol/article/details/131359359
Recomendado
Clasificación