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;
  }
};
相关推荐
工业甲酰苯胺4 小时前
TypeScript枚举类型应用:前后端状态码映射的最简方案
javascript·typescript·状态模式
brzhang4 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
止观止4 小时前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
goms4 小时前
前端项目集成lint-staged
前端·vue·lint-staged
谢尔登4 小时前
【React Natve】NetworkError 和 TouchableOpacity 组件
前端·react.js·前端框架
Lin Hsüeh-ch'in5 小时前
如何彻底禁用 Chrome 自动更新
前端·chrome
augenstern4166 小时前
HTML面试题
前端·html
张可6 小时前
一个KMP/CMP项目的组织结构和集成方式
android·前端·kotlin
G等你下课7 小时前
React 路由懒加载入门:提升首屏性能的第一步
前端·react.js·前端框架
谢尔登7 小时前
【React Native】ScrollView 和 FlatList 组件
javascript·react native·react.js