vue3 封装获取文件后缀和name的工具方法以及本地下载方法

  1. 获取文件后缀
js 复制代码
/**
 * @description:获取附件后缀
 * @param {*} file 文件名称
 * @param {*} isDot 是否显示点 0: 显示 1: 不显示
 */
export const getFileType: (file?: string, isDot?: 0 | 1) => string = (file, isDot = 0) => {
  if (!file) {
    throw "file is null";
  }
  const dot = file.lastIndexOf(".");
  if (dot < 0) {
    throw "file is wrong";
  }
  let end = file.lastIndexOf("?");
  if (end < 0) {
    end = file.length;
  }
  const ext = file.substring(dot + isDot, end).toLowerCase();
  return ext;
};
  1. 获取文件name
js 复制代码
/**
 * @description:获取附件名称
 * @param {*} file 文件名称
 */
export const getFileName: (file?: string) => string = file => {
  if (!file) {
    throw "file is null";
  }
  const dot = file.lastIndexOf(".");
  if (dot < 0) {
    return file;
  }

  let end = file.lastIndexOf("/");

  const name = file.substring(end + 1, dot);
  return name;
};
  1. 有时候后台返回文件地址不是全路径,前端需要根据访问地址拼接成全路径,所以封装全路径拼接方法
js 复制代码
/**
 * @description:获取静态资源完整路径
 * @param {*} url 文件名称
 */

export function getFullUrl(url: string = "") {
  // if (!url) {
  //   throw "url is wrong";
  // }
  const baseURL = import.meta.env.VITE_API_URL as string;
  if (url.indexOf(import.meta.env.VITE_API_URL) !== -1) {
    return url;
  }
  return baseURL + url;
}
  1. 实现下载
js 复制代码
import { getFileName, getFileType } from "@/utils/assetsFile";

/**
 * @description 接收文件地址下载文件
 * @param {String} fileUrl 导出文件地址 (必传)
 * @param {String} fileName 导出的文件名 (非必传)
 * */
export const useOfflineDownload = async (fileUrl: string, fileName?: string, type: "download" | "open" = "download") => {
  try {
    if (type === "open") {
      window.open(fileUrl, "_blank");
      return;
    }
    const name = fileName ? getFileName(fileName) : getFileName(fileUrl);
    const ext = getFileType(fileUrl);

    const exportFile = document.createElement("a");
    exportFile.style.display = "none";
    exportFile.download = `${name}${ext}`;
    exportFile.href = fileUrl;
    document.body.appendChild(exportFile);
    exportFile.click();
    // 去除下载对 url 的影响
    document.body.removeChild(exportFile);
  } catch (error) {
    throw error;
  }
};
相关推荐
李剑一9 分钟前
别再瞎写电子围栏了!这2种动态效果,科技感直接拉满,源码直接抄走!
前端·vue.js·cesium
木易士心28 分钟前
从 MVP 到千万级并发:AI 在前后端开发中的差异化落地指南
前端·后端
葡萄城技术团队30 分钟前
字体与打印:前端开发最常见的三个“为什么”
前端
王夏奇32 分钟前
python中的深浅拷贝和上下文管理器
java·服务器·前端
siger37 分钟前
徒手开荒-我用纯Nodejs+pnpm+monorepo改造了一个多vue2的iframe"微前端"项目
前端·node.js·前端工程化
lichenyang45338 分钟前
海克斯大乱斗攻略网站 —— 从零开发到云服务器部署全记录
前端
你的代码僚机41 分钟前
《别再被 SSO 骗了!前端单点登录原理+避坑指南》
前端
不懂代码的切图仔1 小时前
移动端h5实现横屏在线签名
前端·微信小程序
少卿1 小时前
OpenClaw 的 summarize 技能——开发者的智能摘要利器
前端·后端·程序员
仰望.1 小时前
vue vxe-table 数据分组与排序的实现方式
vue.js·vxe-table