vue实现h5文件上传功能组件

10 篇文章 0 订阅
7 篇文章 0 订阅

该组件为自定义上传文件的功能,使用函数调用实现上传,功能比较简单,后续仍待完善

/**
上传或删除的按钮图片自定义
暂未实现多文件上传功能与预览
暂未实现上传按钮样式自定义功能
**/
<template>
    <div class="upload-box">
      <div v-show="!hideUpload">
        <div class="upload-wrapper">
          <div class="display-flex align-center">
            <img class="plus-icon" :src="require('../../assets/plus.png')" alt="">
            <span class="fileupload-text">添加</span>
          </div>
          <div class="file-desc">{{ text }}</div>
        </div>
        <input
          type="file"
          style="display:none"
          :maxSize="maxSize"
          ref="file"
          @click="e => {e.target.value = '';} "
          :accept="accept"
          @change="getFileData"/>
      </div>
      <div class="file-show" v-show="hideUpload">
        <div class="file-text">
          <img src="../../assets/file-icon.png" alt="">
          <span>{{ fileName }}</span>
        </div>
        <img src="../../assets/clear-file.png" alt="" class="clear-icon" @click.stop="reUpload">
      </div>
    </div>
</template>

<script>
import { upLoad } from '../../utils/api/...'; // 上传接口
//import { getFileName } from '../../utils/common';
// "application/pdf"
// "application/msword"
// application/vnd.openxmlformats-officedocument.wordprocessingml.document"
export default {
  name: "index",
  props: {
    text: { // 上传的按钮文本
      type: String,
      default: "文件上传"
    },
    accept: { // 文件类型,默认多部分
      type: String,
      default: ".doc,.docx,.pdf,.jpg,.jpeg,.gif,.png,.mp3,.mp4,.avi,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf"
    },
    applyType: { // 该文件所属应用类型
      type: String,
      default: "application"
    },
    maxSize: { // 文件大小默认2M
      type: Number,
      default: 2
    },
    limit: { // 文件数量
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      docType: { // 设置word文档类型检查
        '.doc': 'application/msword',
        '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'pdf': 'application/pdf'
      },
      hideUpload: false,
      fileName: '' // 文件名
    }
  },
  methods: {
    clickUpload () {
      if (this.hideUpload === true) {

      } else { // 父组件调用后上传
        this.$refs.file.dispatchEvent(new MouseEvent("click"));
      }
    },
    getFileData () {
      const inputFile = this.$refs.file.files.length > 0 ? this.$refs.file.files[0] : null
      if (inputFile !== null) {
        const accept = this.accept.split(',') || [] // 所有文件类型
        const applyType = inputFile.type.split('/')[0] // 应用类型
        const fileType = '.' + inputFile.type.split('/')[1] // 文件类型
        if (accept.includes('.doc') || accept.includes('.docx') || accept.includes('.pdf')) { // 上传为文档类型
          let has = false
          Object.keys(this.docType).forEach(key => {
            if (this.docType[key] === inputFile.type) {
              has = true
            }
          })
          if (!has) {
            this.$toast('请上传正确的文件类型')
            return
          }
        } else if (!accept.includes(inputFile.type) && !accept.includes(fileType)) {
          switch (this.applyType) {
            case 'application':
              this.$toast('请上传限制的文件类型')
              this.$refs.file.value = null
              return
            case 'audio':
              this.$toast('请上传限制的音频类型')
              this.$refs.file.value = null
              return
            case 'video':
              this.$toast('请上传限制的视频类型')
              this.$refs.file.value = null
              return
          }
        }
        const maxSize = typeof this.maxSize === 'number' ? this.maxSize * 1024 * 1024 : 2 * 1024 * 1024 // init 2M
        if (inputFile.size > maxSize) {
          this.$toast('文件大小已超出上传限制')
          this.$refs.file.value = null
          return
        }
        this.setUpload(inputFile.name, inputFile)
      } else {
        this.$toast('文件上传失败,请重试!')
      }
    },
    setUpload (name = '', file) {
      const formData = new FormData();
      formData.set("fileName", name);
      formData.set("file", file);
      upLoad(formData).then(res => {
        if (res.code === 200) {
          this.hideUpload = true
         //this.fileName = getFileName(res.data.fileName || null).name + getFileName(res.data.fileName || null).ext;
          this.$emit('getFile', res && res.data)
        } else {
          this.$toast('上传失败,请重试!')
        }
        // console.log(res)
      }).catch(err => {
        this.$toast('上传失败,请重试!')
        console.log(err)
      })
    },
    reUpload () {
      this.$refs.file.value = null
      this.hideUpload = false
      this.$emit('getFile', {
        fileName: null,
        url: null
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-box{
  margin: 40px auto;
}
.profile-upload{
  text-align: center;
  padding: 30px 0;
}

.upload-wrapper{
  display: flex;
  flex-direction: column;
  align-items: center;
.file-desc{
  max-width: 354px;
  color: #A2A2A2;
  font-size: 26px;
  text-align: center;
}
}
.plus-icon{
  width: 42px;
  height: 42px;
  margin-right: 17px;
}
.fileupload-text{
  font-size: 28px;
  color: #797979;
}
.file-show{
  margin: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.file-text{
  font-size: 26px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  color: #797979;
  letter-spacing: 1.56px;
  margin-left: 25px;
}
.clear-icon{
  margin-left: 40px;
}
</style>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值