el-upload上传文件到七牛云

2 篇文章 0 订阅
2 篇文章 0 订阅

1.npm install qiniujs 引入文件import * as qiniu from “qiniu-js”;
2.请求接口拿到文件上传token和url前缀
3.在created中写入如下代码拿到当前位置的七牛云存储空间地址

  // 获取七牛云上传地址
    getqiNiu() {
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      };
      const getUrl = qiniu.getUploadUrl(config);
      getUrl.then(res => {
        this.qn = res;
      });
    },

4.引入el-upload组件配置参数

 <el-upload
        :action="qn"
        :class="{hide:hideUpload}"
        class="upload-idCard"
        list-type="picture-card"
        :file-list="defaultImg"
        :onChange="handleChange"
        ref="imgRef"
        :on-preview="handleShow"
        :data="postData"
        :on-error="handleError"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-remove="function(file ,raw){ handleRemovePic('idCard',file ,raw) }"
        :disabled="!IsShowView"
      >`

参数讲解:

	//action 请求七牛云地址
	//hide 当满足条件后隐藏上传框 如上传数量达到则隐藏
	//list-type 组件展示形式 具体配置看element文档
	//file-list 数组对象的形式  页面初始化进入时要展示的图片路径可以push进去默认展示的图片
	 this.defaultImg = [{ url: "你获取的url前缀" + key }];
	 //on-preview 配置这个钩子鼠标放到图片上会出现一个放大镜的查看图片点击触发这个钩子做一下文件预览操作
	 //data是请求参数 一个是token(获取的文件上传凭证) 一个key(文件名)
	 //on-success 上传成功产生的一个回调 回调参数为一个对象 包含了key和hash 拿这两个任何一个值拼接Url前缀即可得到图片的https绝对路径
	 //before-upload 上传文件前触发的钩子 一般用来判断文件类型 和限制文件大小 返回一个布尔值 false 取消上传 true 上传成功
	 //disabled 是false则文件筐可标记 true则不可编辑
	 

5.效果展示
在这里插入图片描述
6.源码附上 单个文件上传功能 可自行扩展

 <template>
  <!-- :http-request="function(val){ customPictureUpload('idCard',val,1) }" -->

  <el-row class="parent" :class="{'file-margin-bom':IsShowView}">
    
      <el-upload
        :action="qn"
        :class="{hide:hideUpload}"
        class="upload-idCard"
        list-type="picture-card"
        :file-list="defaultImg"
        :onChange="handleChange"
        ref="imgRef"
        :on-preview="handleShow"
        :data="postData"
        :on-error="handleError"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-remove="function(file ,raw){ handleRemovePic('idCard',file ,raw) }"
        :disabled="!IsShowView"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="isShowImg" width="50%" size="tiny">
        <img width="70%" :src="myFileUrl" alt />
      </el-dialog>

      <el-dialog :visible.sync="isShowPdf" title="PDF阅读器" width="80%" size="tiny">
        <el-row class="pdfs">
          <vuePdf :myFileUrl="myFileUrl" :pageNum="pageNum" @setValue="handleVale" />
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-pagination @current-change="handleCurrentChange" :total="pageTotalNum" :page-size="1"></el-pagination>

          <el-button @click="handleDownFile" v-if="!showUpload">下载</el-button>
        </span>
      </el-dialog>
    
    <div class="uploadStyleText" v-if="IsShowView">
      <span>备注:仅支持上传JPEG(JPG)GIFPNGPDFEXCELWORD格式</span>
    </div>
  </el-row>
  <!-- <div   class="uploadStyleText" v-if="IsShowView">
                <span>备注:仅支持上传JPEG(JPG)GIFPNGPDF格式</span>
        </div> 
  </div>-->
</template>
   
<script>
import * as qiniu from "qiniu-js";
import vuePdf from "@/components/updata/vue_pdf";
import { getFileType } from "@/api/index.js";
import { deepClone } from "@/utils/index";
import { Message } from "element-ui";

import { getToken } from "@/api/axios";
export default {
  components: {
    vuePdf
  },
  // 文件路径         对应下标   禁言和上传状态 是否显示"下载"按钮
  props: ["fileUrl", "index", "IsShowView", "showUpload"],

  data() {
    return {
      postData: {},
      qn: "",
      // 显示隐藏开关
      hideUpload: false,
      limitCount: 1,
      isShowImg: false,
      isShowPdf: false,
      isType: true,
      myHashUrl: this.fileUrl,
      myFileUrl: "",
      myFileName: "",
      defaultImg: [],
      pageNum: 1,
      SaveData: {
        pageNum: 1,
        pageSize: 10
      },
      pageTotalNum: 1,
      fileImageType: "",
      BASE_URL: "",
      showImage: "http://image.dogohome.com/Flmwv-qq1q8i6liEDw34zecRaQyG"
    };
  },

  watch: {
    fileUrl: {
      handler(newValue, oldValue) {
        //父组件param对象改变会触发此函数
        this.myHashUrl = newValue;
 
        // this.handleFileTypeImg(newValue)
        if (
          this.myHashUrl == undefined ||
          this.myHashUrl == "" ||
          this.myHashUrl == null
        ) {
          this.defaultImg = [];
        } else {
          // this.defaultImg = [{ url: this.showImage }];
          this.handleFileTypeImg(newValue);
          this.defaultImg.length >= this.limitCount && (this.hideUpload = true);
        }
      },
      deep: true
    }
  },

  created() {
    this.getqiNiu();
    if (
      this.fileUrl == undefined ||
      this.fileUrl == "" ||
      this.fileUrl == null
    ) {
      this.defaultImg = [];
    } else {
      this.defaultImg = [{ url: this.showImage }];

      //  this.defaultImg.length >= this.limitCount && (this.hideUpload = true)
      this.hideUpload = true;
    }
    // 打开手册
    this.$bus.$on("updata", () => {
      this.handleShow();
    });
  },

  methods: {
    // 获取七牛云上传地址
    getqiNiu() {
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      };
      const getUrl = qiniu.getUploadUrl(config);
      getUrl.then(res => {
        this.qn = res;
        this.postData.token=this.$store.state.user.setUpdataToken.token
      this.BASE_URL=this.$store.state.user.setUpdataToken.url
      });
    },
    // 判断文件类型
    isFileType(hash) {
      if (hash !== null) {
        getFileType(hash).then(res => {
          if (res.code == 200 && res.data.mimeType != null) {
            let index = res.data.mimeType.lastIndexOf("/");
            this.fileImageType = res.data.mimeType.substring(0, index);
          }
        });
      }
    },

    // async handleGetToken() {
    //    
    //   let uploadObj = await getToken();
    //   this.postData.token = await uploadObj.data.token;
    //   this.BASE_URL = await uploadObj.data.url;
    // },

    // 下载文件
    handleDownFile() {
      // var word = new ActiveXObject("Word.Application");
      //   word.Visible = true;
      //   word.Documents.Open(this.myFileUrl)

      let url = this.myFileUrl;
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      // link.setAttribute("download", "excel.xls");
      document.body.appendChild(link);
      link.click();
    },
    // 上传文件时的钩子函数
    beforeAvatarUpload(file) {
      // this.handleGetToken();
      return this.setFileValidation(file);
    },
    // 选择时触发
    handleChange(file) {
      this.hideUpload = this.defaultImg.length >= this.limitCount;
    },
    // 文件验证
    setFileValidation(file) {
       
      this.postData.key = file.name;
      let arr = file.name.split(".");
      let type = arr[arr.length - 1];
       
      let isJPG =
        (type == "jpg" ||
          type == "png" ||
          type == "gif" ||
          type == "pdf" ||
          type == "ico" ||
          type == "xlsx" ||
          type == "docx") &&
        true;
      !isJPG &&
        this.$message.error(
          "上传的文件不符合规范!,支持格式:png/jpg/gif/ico/pdf"
        );
       
      return isJPG;
    },
    // 成功之后判断类型
    isSuccessFileType(key) {
      let arr = key.split(".");
      return arr[arr.length - 1];
    },
    // 根据类型给文件分配不同的显示图片
    handleFileTypeImg(key) {
      if (this.isSuccessFileType(key) == "xlsx") {
        this.defaultImg = [{ url: "http://image.glijjy.com/excel.png" }];
      } else if (this.isSuccessFileType(key) == "docx") {
        this.defaultImg = [{ url: "http://image.glijjy.com/word.png" }];
      } else if (this.isSuccessFileType(key) == "pdf") {
        this.defaultImg = [{ url: "http://image.glijjy.com/pdf.png" }];
      } else if (
        this.isSuccessFileType(key) == "jpg" ||
        this.isSuccessFileType(key) == "png"
      ) {
        this.defaultImg = [{ url: "http://image.glijjy.com/" + key }];
      } else {
        this.defaultImg = [{ url: this.showImage }];
      }
    },
    // 返回错误
    handleError() {
      Message({
        message: "文件上传失败,服务器中此文件名被占用",
        type: "error",
        duration: 5 * 1000
      });
    },

    // 成功返回
    handleAvatarSuccess(res, file) {
       
      // this.isFileType(res.key);
      this.myFileUrl = this.BASE_URL + res.key;

      this.myHashUrl = res.key;
      this.$emit("assignmentEvent", {
        index: this.index,
        myHashUrl: this.myHashUrl
      });
      this.hideUpload = this.defaultImg.length >= this.limitCount;
      this.handleFileTypeImg(res.key);
    },

    async handleShow() {
     
       
      this.myFileUrl = this.BASE_URL + this.myHashUrl;
      this.isType && (await this.openFile());
    },
    // 如果文件类型是word 或者 exel 则直接打开
    handlePreviewSpecialFormat() {
      // window.open(this.myFileUrl, "_blank")
      this.handleDownFile();
      //  
      // const a = document.createElement('a'); // 创建a标签
      // // a.setAttribute('download', '');// download属性
      // a.setAttribute('href',this.myFileUrl );// href链接
      // a.click();// 自执行点击事件
    },
    // 判断打开的文件类型
    async openFile() {
      let fileType = await getFileType(this.fileUrl);
         
         
      let index = fileType.data.mimeType.lastIndexOf(".");
      this.fileImageType = fileType.data.mimeType.substring(
        index,
        fileType.data.mimeType.length
      );
      //
      if (this.fileImageType == ".sheet" || this.fileImageType == ".document") {
        this.handlePreviewSpecialFormat();
      } else {
        let i = fileType.data.mimeType.lastIndexOf("/");

        this.isShowPdf =
          fileType.data.mimeType.substring(0, i) == "application" && true;
        this.isShowImg =
          fileType.data.mimeType.substring(0, i) == "image" && true;
      }
    },

    // 获得翻译页码
    handleVale(val) {
       
       
      this.pageTotalNum = val;
    },
    // 得到页码
    handleCurrentChange(e) {
      this.pageNum = e;
    },

    beforePictureUpload(file) {},
    //删除方法
    handleRemovePic(name, file, fileList) {
      // alert(3)
      this.hideUpload = false;
      this.$emit("assignmentEvent", { myHashUrl: null, index: this.index });
    }
  }
};
</script>
<style >
.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" scoped>
.pdfs {
  width: 100%;
  height: 500px;
  overflow-y: auto;
}
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.el-pagination,
.el-pager,
.el-pagination__rightwrapper {
  display: flex;
  align-items: center;
}
.parent {
  width: 100px;
  height: 100px;
  // overflow: hidden;
}
.file-margin-bom {
  // margin-bottom:26px !important;
  margin-bottom: 20px !important;
}
// 上传文件 备注 样式

.uploadStyleText {
  /* text-align: right !important; */
  font-size: 13px;
  font-family: PingFang SC;
  font-weight: 400;
  // color: #888;
  width: 600px;

  line-height: 17px;
  color: rgba(210, 211, 217, 1);
  position: absolute;
  top: 100px;
  // left: 2px;
  // z-index: 333;
}

.upload-idCard {
  overflow: hidden;
}
</style>

接下来会发布七牛云配合VueCropper裁切工具双穿base64的图片文件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值