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;
  }
};
相关推荐
小二·5 分钟前
Python Web 开发进阶实战:AI 智能体操作系统 —— 在 Flask + Vue 中构建多智能体协作与自主决策平台
前端·人工智能·python
Knight_AL23 分钟前
Flink 状态管理详细总结:State 分类、Keyed State 实战、Operator State、TTL、状态后端选型
前端·数据库·flink
无心水36 分钟前
17、Go协程通关秘籍:主协程等待+多协程顺序执行实战解析
开发语言·前端·后端·算法·golang·go·2025博客之星评选投票
weixin_638303111 小时前
uniapp组合式和选项式
javascript·vue.js·uni-app
【赫兹威客】浩哥1 小时前
【赫兹威客】框架模板-前端命令行部署教程
前端·vue.js
小妖6661 小时前
javascript 舍去小数(截断小数)取整方法
开发语言·前端·javascript
jay神2 小时前
基于SpringBoot的校园社团活动智能匹配与推荐系统
java·前端·spring boot·后端·毕业设计
一殊酒2 小时前
【前端开发】Vue项目多客户配置自动化方案【一】
前端·vue.js·自动化
切糕师学AI2 小时前
Vue 中 keep-alive 组件的生命周期钩子
前端·vue.js·keep-alive·生命周期·activated·deactivated
daols882 小时前
vue2 表格如何使用 vxe-table 带列头复制单元格内容同步到 excel 中
vue.js·excel·vxe-table