1
0

filePreview.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // lib/filePreview.ts:由 lib/utils.ts 按职责拆分(实现未改)
  2. import { getToken } from '/@/utils/auth/index';
  3. import type { AttachedFile } from '/@/views/ventAI/manageAssistent/types/resource';
  4. import { isImageFile, isPdfFile, isWordFile, isExcelFile } from './fileIcon';
  5. export const fetchPreviewFile = async (url: string, filename: string): Promise<AttachedFile | null> => {
  6. const resp = await fetch(url, { headers: { 'X-Access-Token': getToken() } });
  7. if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
  8. const ext = filename.split('.').pop()?.toLowerCase() || '';
  9. const mimeMap: Record<string, string> = {
  10. md: 'text/markdown',
  11. txt: 'text/plain',
  12. json: 'application/json',
  13. xml: 'text/xml',
  14. yaml: 'text/yaml',
  15. yml: 'text/yaml',
  16. csv: 'text/csv',
  17. // .dxf 是明文,按文本取回后由预览面板本地解析渲染
  18. dxf: 'text/plain',
  19. };
  20. const id = `report-${url}`;
  21. const uploadTime = new Date().toISOString();
  22. if (mimeMap[ext]) {
  23. const content = await resp.text();
  24. return { id, name: filename, size: content.length, type: mimeMap[ext], content, uploadTime };
  25. }
  26. if (isWordFile(filename) || isExcelFile(filename)) {
  27. const arrayBuffer = await resp.arrayBuffer();
  28. return { id, name: filename, size: arrayBuffer.byteLength, type: 'application/octet-stream', arrayBuffer, uploadTime };
  29. }
  30. if (isImageFile(filename) || isPdfFile(filename)) {
  31. const blob = await resp.blob();
  32. const dataUrl = await new Promise<string>((resolve, reject) => {
  33. const reader = new FileReader();
  34. reader.onload = () => resolve(reader.result as string);
  35. reader.onerror = () => reject(reader.error);
  36. reader.readAsDataURL(blob);
  37. });
  38. return { id, name: filename, size: blob.size, type: blob.type, preview: dataUrl, uploadTime };
  39. }
  40. return null;
  41. };