d5827a2146
2. 将查看文档评查结果详情对接接口,采用接口的方式进行查询。
92 lines
3.0 KiB
TypeScript
92 lines
3.0 KiB
TypeScript
import { type LoaderFunctionArgs } from "@remix-run/node";
|
|
import { getUserSession } from "~/api/login/auth.server";
|
|
import { DOCUMENT_URL } from "~/api/axios-client";
|
|
|
|
/**
|
|
* PDF 代理路由
|
|
* 用于在服务器端添加 JWT 认证后获取 PDF 文件
|
|
*/
|
|
export async function loader({ request }: LoaderFunctionArgs) {
|
|
try {
|
|
// 获取 JWT token
|
|
const { frontendJWT } = await getUserSession(request);
|
|
|
|
// 从查询参数获取文件路径和预览标志
|
|
const url = new URL(request.url);
|
|
const filePath = url.searchParams.get("path");
|
|
const isPreview = url.searchParams.get("preview") === "true";
|
|
|
|
// console.log("📄 [PDF Proxy] 请求参数:", {
|
|
// path: filePath,
|
|
// preview: url.searchParams.get("preview"),
|
|
// isPreview: isPreview
|
|
// });
|
|
|
|
if (!filePath) {
|
|
return new Response("缺少文件路径参数", { status: 400 });
|
|
}
|
|
|
|
// 构建完整的文件 URL
|
|
const fileUrl = `${DOCUMENT_URL}${filePath}`;
|
|
|
|
// 使用 JWT 认证获取文件
|
|
const response = await fetch(fileUrl, {
|
|
headers: {
|
|
'Authorization': `Bearer ${frontendJWT}`,
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
return new Response(`获取文件失败: ${response.statusText}`, {
|
|
status: response.status
|
|
});
|
|
}
|
|
|
|
// 获取文件内容
|
|
const blob = await response.blob();
|
|
|
|
// 从路径中提取文件名
|
|
const fileName = filePath.split('/').pop() || 'document.pdf';
|
|
|
|
// 判断文件类型
|
|
const fileExtension = fileName.split('.').pop()?.toLowerCase();
|
|
let contentType = response.headers.get('Content-Type') || 'application/octet-stream';
|
|
|
|
// 🔑 根据文件扩展名强制设置正确的 Content-Type
|
|
if (fileExtension === 'pdf') {
|
|
contentType = 'application/pdf';
|
|
} else if (fileExtension === 'doc' || fileExtension === 'docx') {
|
|
contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
|
}
|
|
|
|
// 设置响应头
|
|
const headers: HeadersInit = {
|
|
'Content-Type': contentType,
|
|
'Cache-Control': 'public, max-age=3600', // 缓存1小时
|
|
};
|
|
|
|
// 根据 preview 参数决定是预览还是下载
|
|
// 默认行为:强制下载(保持向后兼容性)
|
|
if (isPreview) {
|
|
// 在浏览器中预览
|
|
headers['Content-Disposition'] = `inline; filename="${encodeURIComponent(fileName)}"`;
|
|
// console.log("📄 [PDF Proxy] 设置为预览模式 (inline)");
|
|
} else {
|
|
// 强制下载(默认行为)
|
|
headers['Content-Disposition'] = `attachment; filename="${encodeURIComponent(fileName)}"`;
|
|
// console.log("📄 [PDF Proxy] 设置为下载模式 (attachment)");
|
|
}
|
|
|
|
// console.log("📄 [PDF Proxy] 响应头:", headers);
|
|
|
|
// 返回文件
|
|
return new Response(blob, { headers });
|
|
|
|
} catch (error) {
|
|
console.error('PDF 代理错误:', error);
|
|
return new Response(`服务器错误: ${error instanceof Error ? error.message : '未知错误'}`, {
|
|
status: 500
|
|
});
|
|
}
|
|
}
|