- 获取文件后缀
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;
};
- 获取文件
name
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;
};
- 有时候后台返回文件地址不是全路径,前端需要根据访问地址拼接成全路径,所以封装全路径拼接方法
export function getFullUrl(url: string = "") {
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;
}
- 实现下载
import { getFileName, getFileType } from "@/utils/assetsFile";
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();
document.body.removeChild(exportFile);
} catch (error) {
throw error;
}
};