文件预览优化

This commit is contained in:
runny committed 2026-05-30 14:10:44 +08:00
1 parent f91d44ca24
commit 7f66d6f20c
5 files changed
+504 -165

No files matched your search

+99 -76
View File
@@ -54,6 +54,7 @@ const excelPreview = ref<ExcelPreviewData | null>(null);
const officeSrc = ref<string | ArrayBuffer | Blob>('');
const officeKind = ref<OfficeKind>(null);
const officeObjectUrl = ref<string>('');
const officeRenderKey = ref(0);
/**
* 从 URL 或文件名中提取扩展名。
@@ -163,6 +164,66 @@ const clearOfficeObjectUrl = () => {
officeKind.value = null;
};
const applyExcelPreview = (buffer: ArrayBuffer) => {
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
header: 1,
raw: false,
defval: '',
});
const limit = 100;
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
const normalizedRows = rows.map((row) =>
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
);
excelPreview.value = {
sheet_name: sheetName,
sheets: workbook.SheetNames,
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
rows: normalizedRows,
limit,
truncated: matrix.length > limit,
};
};
const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
try {
applyExcelPreview(buffer);
return true;
} catch {
return false;
}
};
const loadSheetPreview = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for excel preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || `HTTP ${res.status}`);
}
excelPreview.value = await res.json();
};
const loadOfficeContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for office preview');
@@ -180,20 +241,29 @@ const loadOfficeContent = async () => {
throw new Error(err?.error || `HTTP ${res.status}`);
}
const blob = await res.blob();
const buffer = await res.arrayBuffer();
clearOfficeObjectUrl();
officeObjectUrl.value = URL.createObjectURL(blob);
officeSrc.value = officeObjectUrl.value;
officeSrc.value = buffer;
officeRenderKey.value += 1;
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
else officeKind.value = null;
};
const loadPdfContent = async () => {
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
if (ext.value === 'doc') {
try {
await loadSheetPreview();
return 'sheet';
} catch {
// Not an excel-disguised-as-doc file, continue with the normal document preview flow.
}
}
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
@@ -209,11 +279,30 @@ const loadPdfContent = async () => {
const blob = await res.blob();
clearOfficeObjectUrl();
const buffer = await blob.arrayBuffer();
const actualExt = (res.headers.get('X-Preview-Actual-Ext') || '').toLowerCase();
const blobType = (blob.type || '').toLowerCase();
const isDocxPayload = actualExt === 'docx' || blobType.includes('wordprocessingml.document');
const isExcelPayload = ['xlsx', 'xls'].includes(actualExt) || blobType.includes('spreadsheetml.sheet') || blobType.includes('application/vnd.ms-excel');
if (isExcelPayload) {
await loadSheetPreview();
return 'sheet';
}
if (!blobType.includes('pdf') && tryApplyExcelPreview(buffer)) {
return 'sheet';
}
if (isDocxPayload) {
officeSrc.value = buffer;
officeRenderKey.value += 1;
officeKind.value = 'docx';
return 'office';
}
let fallbackType = 'application/octet-stream';
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
return 'iframe';
};
const loadBinaryContent = async () => {
@@ -263,8 +352,7 @@ const loadContent = async () => {
}
isLoading.value = true;
try {
await loadPdfContent(); // This fetches as Blob, and sets officeObjectUrl which will be used in iframeSrc
resolvedMode.value = 'iframe';
resolvedMode.value = await loadPdfContent();
} catch (e: any) {
error.value = e?.message || `Failed to preview ${ext.value}`;
resolvedMode.value = 'iframe';
@@ -291,54 +379,9 @@ const loadContent = async () => {
return;
}
if (preferredMode.value === 'sheet') {
if (!props.agentId) {
error.value = 'agent_id is required for excel preview';
return;
}
isLoading.value = true;
try {
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || `HTTP ${res.status}`);
}
const buffer = await res.arrayBuffer();
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
header: 1,
raw: false,
defval: '',
});
const limit = 100;
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
const normalizedRows = rows.map((row) =>
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
);
excelPreview.value = {
sheet_name: sheetName,
sheets: workbook.SheetNames,
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
rows: normalizedRows,
limit,
truncated: matrix.length > limit,
};
await loadSheetPreview();
resolvedMode.value = 'sheet';
} catch (e: any) {
error.value = e?.message || 'Failed to preview excel';
@@ -423,16 +466,6 @@ watch(
<div class="min-w-0">
<div class="label-field tracking-wide">{{ t('filePreview.title') }}</div>
<div class="mt-1 font-semibold text-primary break-words">{{ file.name }}</div>
<button type="button" @click="downloadFile" :disabled="isDownloading" class="btn-secondary btn-sm mt-2 inline-flex border-brand-200 text-brand-700 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed">
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
</div>
@@ -491,11 +524,15 @@ watch(
>
<VueOfficeDocx
v-if="officeKind === 'docx'"
:key="`docx-${officeRenderKey}`"
:src="officeSrc"
@rendered="error = ''"
@error="error = 'DOCX render failed'"
style="height: 100%; width: 100%;"
/>
<VueOfficeExcel
v-else-if="officeKind === 'excel'"
:key="`excel-${officeRenderKey}`"
:src="officeSrc"
style="height: 100%; width: 100%;"
/>
@@ -523,20 +560,6 @@ watch(
<div class="mt-2 text-sm text-muted">
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div>
<div class="mt-4 flex gap-3">
<button
type="button"
@click="downloadFile"
:disabled="isDownloading"
class="btn-primary btn-sm inline-flex"
>
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div>
</div>
<iframe
v-else