vue3 封装获取文件后缀和name的工具方法以及本地下载方法

  1. 获取文件后缀
/**
 * @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
/**
 * @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. 有时候后台返回文件地址不是全路径,前端需要根据访问地址拼接成全路径,所以封装全路径拼接方法

/**
 * @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. 实现下载
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;
  }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值