import axios from 'axios';
|
import html2Canvas from 'html2canvas';
|
import JsPDF from 'jspdf';
|
import { MAIN_URL } from '/@/constants';
|
import type { BankImage } from '/@/projectCom/artImage/bank/image/types';
|
|
export const getFullFilePath = (url, fileName) => {
|
return `${url}/${fileName}`;
|
};
|
|
export const getBankImageUrl = (bankImage: BankImage, isRelative = false, baseUrl = MAIN_URL) => {
|
const urlArr = bankImage?.StorageHouse ? [bankImage?.StorageHouse, bankImage?.StorageCode] : [bankImage?.StorageCode];
|
if (!isRelative) {
|
urlArr.unshift(baseUrl);
|
}
|
const fullPath = urlArr.join('/');
|
return fullPath;
|
};
|
|
export const getFileUrl = (storageHouse: string, storageCode: string, isRelative = false, baseUrl = MAIN_URL) => {
|
if (!storageCode) return '';
|
const urlArr = storageHouse ? [storageHouse, storageCode] : [storageCode];
|
if (!isRelative) {
|
urlArr.unshift(baseUrl);
|
}
|
const fullPath = urlArr.join('/');
|
return fullPath;
|
};
|
|
export const downloadFileByUrl = (relativeUrl, baseUrl = MAIN_URL) => {
|
if (relativeUrl) {
|
// 使用 axios,防止类似于 pdf 在 edge 中被直接打开而不是下载
|
axios(baseUrl + '/' + relativeUrl, {
|
responseType: 'blob', //重要代码
|
}).then((res) => {
|
const url = window.URL.createObjectURL(new Blob([res.data]));
|
const link = document.createElement('a');
|
link.href = url;
|
const fileName = relativeUrl.split('/').at(-1);
|
link.setAttribute('download', fileName);
|
document.body.appendChild(link);
|
link.click();
|
link.remove();
|
});
|
}
|
};
|
|
export const downloadFileByStorageHouseAndStorageCode = (storageHouse, storageCode) => {
|
const relativeUrl = getFileUrl(storageHouse, storageCode, true);
|
downloadFileByUrl(relativeUrl);
|
};
|
|
// 调整比例,可以解决下载 pdf 右侧显示不全的问题
|
export const downloadHtmlPdf = (selector: string, name: string, rate = 1.455) => {
|
const scale = 2;
|
html2Canvas(document.querySelector(selector), {
|
allowTaint: true, // 开启跨域
|
scale, // 提升画面质量,但是会增加文件大小
|
}).then(function (canvas) {
|
const contentWidth = canvas.width / scale;
|
const contentHeight = canvas.height / scale;
|
const PDF = new JsPDF(undefined, 'pt', [contentWidth, contentHeight]);
|
const pageData = canvas.toDataURL('image/jpeg', 1.0);
|
PDF.addImage(pageData, 'JPEG', 0, 0, contentWidth / rate, contentHeight / rate);
|
PDF.save(name + '.pdf');
|
});
|
};
|
/**
|
* 文件大小字节转换为XXX
|
* @param size 字节大小
|
* @returns {string|*}
|
*/
|
export const convertFileSize = (size) => {
|
if (!size && size !== 0) return '';
|
if (size < pow1024(1)) return size + ' B';
|
if (size < pow1024(2)) return (size / pow1024(1)).toFixed(2) + ' KB';
|
if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2) + ' MB';
|
if (size < pow1024(4)) return (size / pow1024(3)).toFixed(2) + ' GB';
|
return (size / pow1024(4)).toFixed(2) + ' TB';
|
};
|
|
// 求次幂
|
function pow1024(num) {
|
return Math.pow(1024, num);
|
}
|