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;
  }
};
相关推荐
2501_940007892 分钟前
Flutter for OpenHarmony三国杀攻略App实战 - 战绩记录功能实现
开发语言·javascript·flutter
摘星编程7 分钟前
React Native + OpenHarmony:自定义useEllipsis省略号处理
javascript·react native·react.js
2401_8590490817 分钟前
git submodule update --init --recursive无法拉取解决
前端·chrome·git
这是个栗子35 分钟前
【Vue代码分析】前端动态路由传参与可选参数标记:实现“添加/查看”模式的灵活路由配置
前端·javascript·vue.js
刘一说43 分钟前
Vue 动态路由参数丢失问题详解:为什么 `:id` 拿不到值?
前端·javascript·vue.js
熊猫钓鱼>_>1 小时前
动态网站发布部署核心问题详解
前端·nginx·容器化·网页开发·云服务器·静态部署
方也_arkling1 小时前
elementPlus按需导入配置
前端·javascript·vue.js
爱吃大芒果1 小时前
Flutter for OpenHarmony 实战: mango_shop 资源文件管理与鸿蒙适配
javascript·flutter·harmonyos
我的xiaodoujiao1 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
沛沛老爹1 小时前
Web开发者转型AI:多模态Agent视频分析技能开发实战
前端·人工智能·音视频