liding
4 天以前 6eeb82e56306d645a290a0f5ba202efe3ef2385d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { getJavaApi } from '@/utils/java-api'
import { resolveAttachmentUrl, validateAttachmentBlob } from '@/utils/attachment'
 
export function reportFilename(value, extension) {
  const name = String(value || '报告').replace(/[\\/:*?"<>|\x00-\x1f]/g, '-').trim() || '报告'
  return name.replace(/\.(docx|pdf)$/i, '') + '.' + extension
}
 
// 只替换末尾扩展名,兼容目录名、报告编号中含小数点的历史文件。
export function reportPdfPath(path) {
  return path.replace(/\.docx?$/i, '.pdf')
}
 
// 下单页沿用已有报告文件入口,鉴权信息只发送给本系统。
export async function loadReportFile(path, signal) {
  const url = resolveAttachmentUrl(path, 2)
  const backend = new URL(getJavaApi(), window.location.origin)
  const target = new URL(url, window.location.origin)
  const isBackend = target.origin === backend.origin
    && target.pathname.startsWith(backend.pathname.replace(/\/$/, '') + '/')
  const { data } = await axios.get(url, {
    responseType: 'blob', signal,
    headers: isBackend && getToken() ? { Authorization: 'Bearer ' + getToken() } : {}
  })
  return data
}
 
export async function validateReportPreview(blob, format) {
  if (!(blob instanceof Blob) || !blob.size) throw new Error('报告内容为空,请重试或联系管理员')
  await validateAttachmentBlob(blob, '报告.' + format)
  const header = new Uint8Array(await blob.slice(0, 5).arrayBuffer())
  const isPdf = String.fromCharCode(...header) === '%PDF-'
  const isDocx = header[0] === 0x50 && header[1] === 0x4b
  if (format === 'pdf' ? !isPdf : !isDocx) throw new Error('未获取到有效的报告文件,请重试或联系管理员')
  // 静态文件服务器可能返回 octet-stream,PDF 阅读器需要明确的 MIME 类型。
  return new Blob([blob], { type: format === 'pdf' ? 'application/pdf'
    : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })
}