Newer
Older
KaiFengPC / src / directive / el-downLoad / index.js
@zhangdeliang zhangdeliang on 23 May 1 KB 初始化项目
//屏蔽右键功能
// 添加自定义v-down指令
// let baseDownloadUrl = process.env.VUE_APP_BASE_API; // 域名
export default {
  mounted(el, binding, vnode) {
    const { value } = binding;
    el.style.cssText = "cursor: pointer;color:#1890ff;";
    el.style.width = "100%";
    el.addEventListener("click", () => {
      console.log(binding);
      let link = document.createElement("a"); // 创建a标签
      link.style.display = "none";
      let url = ""; //文件地址
      let name = ""; //文件名称
      // 如果指令绑定的值为对象则取名称和地址,否则直接取值(即地址)
      if (binding.value instanceof Object) {
        url = binding.value.scanAttachUrl;
        name = binding.value.scanAttachName;
      } else {
        url = binding.value; // 设置下载地址
      }
      // 这里是将url转成blob地址,
      fetch(url)
        .then((res) => res.blob())
        .then((blob) => {
          // 将链接地址字符内容转变成blob地址
          link.href = URL.createObjectURL(blob);
          if (binding.value instanceof Object) {
            link.download = name; //取名称
          } else {
            link.download = url.split("/")[url.split("/").length - 1]; //取名称
          }
          document.body.appendChild(link);
          link.click();
        });
    });
  },
};