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;
  }
};
相关推荐
q1cheng4 分钟前
基于Spring Boot + Vue项目online_learn的权限控制机制分析
前端
扶苏100211 分钟前
深入理解 Vue 3 的 watch
前端·javascript·vue.js
前端 贾公子13 分钟前
组件 v-model 的封装实现原理及 Input 组件的核心实现(上)
服务器·前端·javascript
老骥伏枥~13 分钟前
基于Spring Boot + Vue.js的图书管理系统
vue.js·spring boot·后端
weixin1997010801617 分钟前
亚马逊商品详情页前端性能优化实战
前端·性能优化
全栈前端老曹19 分钟前
【Redis】 监控与慢查询日志 —— slowlog、INFO 命令、RedisInsight 可视化监控
前端·数据库·redis·缓存·全栈·数据库监控·slowlog
扶苏100222 分钟前
Vue 3 的组合式 API(Composition API)优势
前端·javascript·vue.js
code袁36 分钟前
基于Springboot+Vue的家教小程序的设计与实现
vue.js·spring boot·小程序·vue·家教小程序
万少38 分钟前
这可能是程序员离用AI赚钱最容易的一个机会了
前端·ai编程
范什么特西41 分钟前
狂神---死锁
java·前端·javascript