vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue视频 图片上传

Vue实现自定义视频和图片上传的示例代码

作者:Ann_R

这篇文章主要为大家详细介绍了如何通过Vue实现自定义视频和图片上传的功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下

使用el-upload 上传视频总是报404错误,具体也不知道什么原因(如有知道的请评论告知,谢谢),去网上查了很多,代码写法确定是没有问题的,最后改为axios上传视频,就没出错了,顺便总结下图片上传

<template>
  <div class="body">
    <span>测试</span>
    <span>视频上传</span>
    <!-- style="display:none;" 隐藏input框 -->
    <input style="display:none;" class="input-video" multiple type="file" accept="video/*"
      @change="uploadVideo11($event)">
    <div v-if="!videoUrl" class="no-bg wh">
      <el-progress class="progress-video" v-if="progress" type="circle" :percentage="videoUploadPercent"></el-progress>
      <div v-if="!progress" @click="uploadVideo">
        <span>点击上传视频</span>
      </div>
    </div>
    <video v-else="videoUrl" class="wh" v-bind:src="videoUrl" controls="controls">
      您的浏览器不支持视频播放
    </video>

    <span>-------------------------------------------------------------------------</span>

    <span>图片上传</span>
    <!-- <el-upload 
      :disabled="disabled"  删除图片后禁止弹窗弹出
      :action="this.$store.state.updataurl"  图片上传路径
      :headers="headers"  请求头
      :show-file-list="false" 文件列表
      :on-success="handleAvatarSuccess" 上传成功回调
      :before-upload="beforeAvatarUpload" 上传前回调
      :on-remove="handleRemove" 移除回调
      :on-progress="picUploadProcess" 上传进度条
      class="wh" > -->
    <el-upload :disabled="disabled" :action="this.$store.state.updataurl" :headers="headers" :show-file-list="false"
      :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-remove="handleRemove"
      :on-progress="picUploadProcess" class="wh">
      <div v-if="cover" class="change-img wh">
        <!-- 地址拼接 -->
        <img :src="picUrl + cover" class="wh" />
        <div class="change">
          <span class="arr">更换</span>
          <span>&nbsp;|&nbsp;</span>
          <span class="arr" @click="handleRemove">删除</span>
        </div>
      </div>
      <div v-else class="no-bg wh">
        <el-progress v-if="picFlag" type="circle" :percentage="picUploadPercent"></el-progress>
        <div v-else @click="disabled = false">
          <span class="note">点击上传封面图片</span>
        </div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      // 视频
      videoUrl: '', //视频播放地址
      progress: false,
      videoUploadPercent: 0,

      // 图片
      picUrl: this.$store.state.baseurl, //图片前缀
      disabled: false,  //删除图片后禁止文件选择弹窗弹出
      picFlag: false,   //进度条显示标识
      picUploadPercent: 0,
      cover: ''
    }
  },
  computed: {
    headers() {
      return {
        Authorization: this.$store.getters.token || localStorage.getItem("token"),
        // soloFileName: 'video',   //和后端协商的默认标识
      };
    },
  },
  methods: {
    // 视频上传
    uploadVideo() {
      let ipFile = document.querySelector('.input-video')
      ipFile.click();
      this.videoUploadPercent = 0
    },
    async uploadVideo11(e) {
      // console.log("uploadVideo11", e)
      // console.log(e.target.files[0])
      this.progress = true
      let file = e.target.files[0]
      console.log("file", file)
      // multipart/form-data 格式
      let formData = new FormData()
      formData.append('file', file)
      let config = {
        //添加请求头
        headers: {
          Authorization: this.$store.getters.token || localStorage.getItem("token"),
          "Content-Type": "multipart/form-data"
        },
        // 添加进度条
        onUploadProgress: (progressEvent) => {
          this.videoUploadPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(0)) * 1
          // console.log("this.videoUploadPercent", this.videoUploadPercent)
        }
      };
      axios.post(this.$store.state.videoUploadUrl, formData, config, { timeout: 1000 * 60 * 2 })	 //设置超时2分钟
        .then(async (res) => {
          console.log("视频上传", res);
          this.videoUrl = res.data.data.playUrl  //端传过来的视频播放地址
          if (this.videoUrl) {
            this.progress = false
            this.$message({
              message: '上传成功',
              type: 'success'
            });
          }
        }).catch(err => {
          this.progress = false
          console.log(err);
          this.$message.error({
            message: '上传失败'
          });
        })
    },

    // 图片上传
    handleAvatarSuccess: function (response, file, fileList) {
      if (file.response.code == 200) {
        this.cover = file.response.data.src;  //后端传过来的图片地址
        this.picFlag = false
        this.picUploadPercent = 0
      }
    },
    handleRemove(file) {
      this.cover = ''
      this.disabled = true
      // 1.获取将要删除图片的临时路径
      // const filePath = file.response.data.tmp_path
      // // 2.从pics数组中,找到图片对应的索引值
      // const i = this.formData.pics.findIndex(x => x.pic === filePath)
      // // 3.调用splice方法,移除图片信息
      // this.formData.splice(i, 1)
    },
    beforeAvatarUpload(file) {
      const isIMG = /^image\/(jpe?g|png|gif)$/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isIMG) {
        this.$message.error("上传图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isIMG && isLt2M;
    },
    picUploadProcess(event, file, fileList) {
      this.picFlag = true;
      this.picUploadPercent = file.percentage.toFixed(0) * 1;
    },
  }
}
</script>

<style lang="less" scoped>
// 进度条
/deep/ .el-progress-circle {
  height: 100px !important;
  width: 100px !important;
}

.body {
  display: flex;
  flex-direction: column;
}

.no-bg {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #000000;
  background-color: #FBFBFC;
  border-radius: 5px;
  cursor: pointer; //变小手
}

.wh {
  width: 320px;
  height: 180px;
  border-radius: 5px;
}

.change-img {
  position: relative;

  .change {
    opacity: 0;
    position: absolute;
    bottom: 8%;
    left: 35%;
    padding: 6px 11px;
    background-color: rgba(0, 0, 0, 0.7);
    border-radius: 4px;
    color: #FFFFFF;
  }
}

.change-img:hover .change {
  opacity: 1;
}

.arr {
  cursor: default;
}
</style>

到此这篇关于Vue实现自定义视频和图片上传的示例代码的文章就介绍到这了,更多相关Vue视频 图片上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文