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;
  }
};
相关推荐
Justin3go8 小时前
HUNT0 上线了——尽早发布,尽早发现
前端·后端·程序员
怕浪猫8 小时前
第一章 JSX 增强特性与函数组件入门
前端·javascript·react.js
铅笔侠_小龙虾8 小时前
Emmet 常用用法指南
前端·vue
钦拆大仁9 小时前
跨站脚本攻击XSS
前端·xss
前端小L9 小时前
贪心算法专题(十):维度权衡的艺术——「根据身高重建队列」
javascript·算法·贪心算法
VX:Fegn089510 小时前
计算机毕业设计|基于springboot + vue校园社团管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·课程设计
Fortunate Chen10 小时前
类与对象(下)
java·javascript·jvm
ChangYan.11 小时前
直接下载源码但是执行npm run compile后报错
前端·npm·node.js
skywalk816311 小时前
在 FreeBSD 上可以使用的虚拟主机(Web‑Hosting)面板
前端·主机·webmin