Files
Academic-Affairs-System/web/src/api/excel.ts
T

78 lines
2.7 KiB
TypeScript

import type { AxiosRequestConfig } from 'axios'
import http from './http'
function responseFileName(header: string | undefined, fallback: string) {
if (!header) return fallback
const encoded = header.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
if (encoded) return decodeURIComponent(encoded)
const plain = header.match(/filename="?([^";]+)"?/i)?.[1]
return plain || fallback
}
function uniqueFallbackName(path: string, fallback: string) {
if (/template|模板/i.test(path) || !fallback.includes('.')) return fallback
const dot = fallback.lastIndexOf('.')
const now = new Date()
const parts = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
}).formatToParts(now).reduce<Record<string, string>>((result, item) => {
result[item.type] = item.value
return result
}, {})
const milliseconds = String(now.getMilliseconds()).padStart(3, '0')
const random = crypto.getRandomValues(new Uint8Array(3))
const code = Array.from(random, value => value.toString(16).padStart(2, '0')).join('').toUpperCase()
const suffix = `${parts.year}${parts.month}${parts.day}-${parts.hour}${parts.minute}${parts.second}-${milliseconds}-${code}`
return `${fallback.slice(0, dot)}-${suffix}${fallback.slice(dot)}`
}
export async function downloadApiFile(
path: string,
fallbackName: string,
config?: AxiosRequestConfig,
) {
const response = await http.get(path, {
...config,
responseType: 'blob',
})
const url = URL.createObjectURL(response.data)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = responseFileName(
response.headers['content-disposition'], uniqueFallbackName(path, fallbackName),
)
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
URL.revokeObjectURL(url)
}
export async function downloadApiPostFile(
path: string,
payload: unknown,
fallbackName: string,
) {
const response = await http.post(path, payload, { responseType: 'blob' })
const url = URL.createObjectURL(response.data)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = responseFileName(
response.headers['content-disposition'], uniqueFallbackName(path, fallbackName),
)
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
URL.revokeObjectURL(url)
}
export async function importExcel(path: string, file: File, validateOnly = false) {
const form = new FormData()
form.append('file', file)
return http.post(path, form, {
params: validateOnly ? { validateOnly: true } : undefined,
headers: { 'Content-Type': 'multipart/form-data' },
timeout: 60000,
})
}