You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不下载直接将mozilla pdf.js修改后的PDF跨域保存到个人服务器

解决方案

核心问题原因

  • 直接抓取pdf.js渲染用的blob URL无法获取包含原始内容+修改内容的完整PDF二进制流,仅能拿到部分渲染数据,是文件损坏的核心诱因
  • 未明确指定Blob的MIME类型为application/pdf,后端接收时若自动做编码转换会破坏二进制结构
  • 跨域请求规则配置错误,可能导致二进制数据传输截断
  • 后端接收后未直接写入原始二进制流,额外编码操作会损坏文件

前端修复(无需下载,直接内存获取完整修改后PDF上传)

优先使用pdf.js官方提供的导出API获取完整文档流,不要直接抓取渲染层的blob URL,修正后代码如下:

// 若使用pdf.js官方viewer,直接调用全局API导出完整修改后的PDF二进制流
const fullPdfUint8Array = await PDFViewerApplication.pdfDocument.saveDocument();
// 明确指定MIME类型为application/pdf
const fullPdfBlob = new Blob([fullPdfUint8Array], { type: 'application/pdf' });

const formData = new FormData();
formData.append("file", fullPdfBlob, "modified.pdf");

// 上传请求配置
await fetch('http://localhost:54402/Controller/Methode', {
    method: 'POST',
    mode: 'cors', // 明确开启跨域模式
    credentials: 'include', // 若不需要传递cookie可删除该行
    body: formData
})
.then(res => res.json())
.then(data => console.log('上传结果', data));

如果是自行封装的pdf.js调用场景,替换第一步的导出逻辑为对应pdf实例的save()方法获取Uint8Array即可,逻辑完全一致。

后端C#修复

第一步:配置跨域规则

先安装Microsoft.AspNet.CorsNuget包,在项目启动配置中添加跨域允许规则:

// 写入WebApiConfig.Register 或 MVC全局配置中
config.EnableCors(new EnableCorsAttribute("http://你的前端部署域名", "*", "POST") { 
    SupportsCredentials = true 
});

同时配置允许OPTIONS预检请求,避免跨域调用被拦截。

第二步:完善文件保存逻辑

直接写入原始二进制流,不要做任何文本编码转换:

[HttpPost]
public ActionResult Methode(HttpPostedFileBase file)
{
    if (file == null || file.ContentLength == 0)
        return Json(new { success = false, msg = "文件为空" });
    
    // 替换为你实际的保存目录,确保目录有写入权限
    string saveDir = Server.MapPath("~/PdfUploads");
    if (!Directory.Exists(saveDir))
        Directory.CreateDirectory(saveDir);
    
    string fullSavePath = Path.Combine(saveDir, Path.GetFileName(file.FileName));
    // 直接复制原始流写入文件
    using (var stream = new FileStream(fullSavePath, FileMode.Create, FileAccess.Write))
    {
        file.InputStream.CopyTo(stream);
    }
    
    return Json(new { success = true, savePath = fullSavePath });
}

额外配置检查

  • 若PDF文件超过4MB,修改web.config配置放开IIS上传大小限制:
<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="104857600" /> <!-- 最大100MB,按需调整 -->
    </requestFiltering>
  </security>
</system.webServer>
  • 所有环节禁止对PDF二进制流做UTF-8、GBK等文本编码转换,全程传递原始二进制数据即可。

内容的提问来源于stack exchange,提问作者Anandhan J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:45:01