fec648f6fc
前端上传桥与降级桥透传 uploadOss;品牌页提交时 fileUrl 优先取上传响应的 OSS url,localPath 仅作旧桌面桥兜底。
173 lines
6.1 KiB
TypeScript
173 lines
6.1 KiB
TypeScript
/**
|
||
* Web 浏览器降级桥
|
||
*
|
||
* 桌面客户端(pywebview)环境下 window.pywebview.api 提供文件对话框、任务队列、本地存档等能力;
|
||
* 前端 Web 独立部署后页面运行在纯浏览器中,没有该桥。
|
||
* 本模块用浏览器原生能力模拟其中"可全链路完成"的方法(文件选择 → 上传 Java / 模板下载 / 配置存取),
|
||
* 其余方法保持 undefined,让页面代码走既有的"请在本地客户端中打开"降级分支。
|
||
*/
|
||
|
||
import type { DesktopConfig, DesktopConfigUpdate, PywebviewApi } from './pywebview'
|
||
import { extractErrorMessage, http } from '@/shared/api/http'
|
||
|
||
/** 虚拟路径 → 浏览器 File 对象(虚拟路径仅存活于当前页面会话,刷新即失效) */
|
||
const webFileMap = new Map<string, File>()
|
||
let webFileSeq = 0
|
||
|
||
const CONFIG_STORAGE_KEY = 'web_desktop_config'
|
||
|
||
function readStoredConfig(): DesktopConfig {
|
||
try {
|
||
const raw = window.localStorage.getItem(CONFIG_STORAGE_KEY) || ''
|
||
return raw ? (JSON.parse(raw) as DesktopConfig) : {}
|
||
} catch {
|
||
return {}
|
||
}
|
||
}
|
||
|
||
function writeStoredConfig(data: DesktopConfigUpdate): DesktopConfig {
|
||
const merged: DesktopConfig = { ...readStoredConfig(), ...data }
|
||
try {
|
||
window.localStorage.setItem(CONFIG_STORAGE_KEY, JSON.stringify(merged))
|
||
} catch {
|
||
/* 本地存储异常时忽略:配置读取仍是空对象 */
|
||
}
|
||
return merged
|
||
}
|
||
|
||
/** 打开浏览器文件选择框;用户取消时返回空数组(不阻塞后续选择) */
|
||
function pickBrowserFiles(accept = '', multiple = false): Promise<File[]> {
|
||
return new Promise((resolve) => {
|
||
const input = document.createElement('input')
|
||
input.type = 'file'
|
||
input.accept = accept
|
||
input.multiple = multiple
|
||
input.style.display = 'none'
|
||
document.body.appendChild(input)
|
||
const cleanup = () => {
|
||
input.remove()
|
||
}
|
||
input.addEventListener('cancel', () => {
|
||
// 现代浏览器支持 file input 的 cancel 事件;旧浏览器取消时 Promise 保持挂起(下次选择会覆盖 UI,无副作用)
|
||
cleanup()
|
||
resolve([])
|
||
})
|
||
input.onchange = () => {
|
||
const files = Array.from(input.files || [])
|
||
cleanup()
|
||
resolve(files)
|
||
}
|
||
input.click()
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 把浏览器 File 注册为虚拟路径(形如 web-file:<序号>/<文件名>)。
|
||
* 虚拟路径满足页面既有的文件名规整逻辑(baseName 按 / 切分、.xlsx 后缀校验)。
|
||
*/
|
||
function registerWebFiles(files: File[]): string[] {
|
||
return files.map((file) => {
|
||
const id = `web-file:${++webFileSeq}/${file.name}`
|
||
webFileMap.set(id, file)
|
||
return id
|
||
})
|
||
}
|
||
|
||
/** 扩展名过滤('xlsx,xls,csv')转 input accept('.xlsx,.xls,.csv') */
|
||
function buildAccept(extensions?: string): string {
|
||
return (extensions || '')
|
||
.split(',')
|
||
.map((item) => item.trim())
|
||
.filter(Boolean)
|
||
.map((ext) => (ext.startsWith('.') ? ext : `.${ext}`))
|
||
.join(',')
|
||
}
|
||
|
||
/** 触发浏览器下载(a[download]) */
|
||
function triggerAnchorDownload(url: string, filename: string) {
|
||
const link = document.createElement('a')
|
||
link.href = url
|
||
link.download = filename
|
||
link.style.display = 'none'
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
link.remove()
|
||
}
|
||
|
||
/** 模板文件下载:先 HEAD 预检(含 content-type 防 SPA/vite 回退 HTML),文件不存在时返回失败而非静默 404 */
|
||
async function downloadTemplateFile(path: string, filename: string) {
|
||
try {
|
||
const resp = await window.fetch(path, { method: 'HEAD' })
|
||
const contentType = resp.headers.get('content-type') || ''
|
||
if (!resp.ok || contentType.includes('text/html')) {
|
||
return { success: false, error: `模板文件不存在(HTTP ${resp.status})` }
|
||
}
|
||
} catch {
|
||
return { success: false, error: '模板文件不可访问' }
|
||
}
|
||
triggerAnchorDownload(path, filename)
|
||
return { success: true, path: filename }
|
||
}
|
||
|
||
/** 浏览器环境下的桥降级实现:只提供浏览器可全链路完成的方法 */
|
||
export const webFallbackApi: PywebviewApi = {
|
||
/** 选择文件(Excel/CSV 等),返回虚拟路径列表 */
|
||
async select_files(options) {
|
||
const accept = buildAccept(options?.filters?.[0]?.extensions)
|
||
const files = await pickBrowserFiles(accept, options?.multiple !== false)
|
||
if (!files.length) return null
|
||
return { paths: registerWebFiles(files) }
|
||
},
|
||
|
||
/** 选择品牌 xlsx 文件(多选) */
|
||
async select_brand_xlsx_files() {
|
||
const files = await pickBrowserFiles('.xlsx', true)
|
||
return registerWebFiles(files)
|
||
},
|
||
|
||
/** 虚拟路径 → 浏览器 File → 上传 Java;uploadOss=true 时同时上传公开 OSS(品牌检测等服务端化工具用) */
|
||
async upload_file_to_java(filePath, relativePath, uploadOss) {
|
||
const file = typeof filePath === 'string' ? webFileMap.get(filePath) : undefined
|
||
if (!file) {
|
||
return { success: false, error: '文件不存在,请重新选择' }
|
||
}
|
||
const form = new FormData()
|
||
form.append('file', file, file.name)
|
||
if (relativePath) {
|
||
form.append('relativePath', relativePath)
|
||
}
|
||
if (uploadOss) {
|
||
form.append('uploadToOss', 'true')
|
||
form.append('moduleType', 'BRAND')
|
||
}
|
||
try {
|
||
// http 实例对 /newApi 前缀自动附带 Bearer;FormData 的 Content-Type 交由浏览器自动生成(含 boundary)
|
||
const response = await http.post('/newApi/api/files/upload', form, { timeout: 120000 })
|
||
return response.data
|
||
} catch (error) {
|
||
return { success: false, error: extractErrorMessage(error) }
|
||
}
|
||
},
|
||
|
||
/** 品牌文档模板(xlsx)直接浏览器下载 */
|
||
async save_template_xlsx() {
|
||
const name = '品牌文档格式_模板.xlsx'
|
||
return downloadTemplateFile(`/static/${encodeURIComponent(name)}`, name)
|
||
},
|
||
|
||
/** 文件夹方式上传模板(zip)直接浏览器下载 */
|
||
async save_template_zip() {
|
||
const name = '模板2-以文件夹方式上传.zip'
|
||
return downloadTemplateFile(`/static/${encodeURIComponent(name)}`, name)
|
||
},
|
||
|
||
/** 代理等桌面配置降级到 localStorage(Web 环境与桌面端配置相互独立) */
|
||
async read_config() {
|
||
return readStoredConfig()
|
||
},
|
||
|
||
async save_config(data) {
|
||
return writeStoredConfig(data)
|
||
},
|
||
}
|