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

Next.js API如何返回文件实现浏览器预览而非触发下载?

如何让服务器返回docx文件时触发浏览器预览而非下载?

我尝试在浏览器中返回docx文件以供客户端预览,试过两种方式:

const rs = fs.createReadStream(fullPath);
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
rs.pipe(res);
const file = await fs.readFile(fullPath); // 此处fs从fs/promises导入
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
res.status(200).send(file);

问题在于两种方式都会触发文件下载,而我想要的是文件预览效果。在微软Edge浏览器中打开测试docx文件时,会跳转到网页版Microsoft Word进行预览,也可以通过iframe查看文件,但将自己的API地址传入iframe时提示无法打开文件,大概率是服务器的文件响应方式不正确。

解决方案

核心是通过设置Content-Disposition响应头,告诉浏览器以内联方式处理文件,而非强制下载:

  1. 添加Content-Disposition头
    在原有响应头基础上,添加inline类型的Content-Disposition,同时指定文件名(可选,但能提升体验):

    res.setHeader("Content-Disposition", "inline; filename=\"你的文件名.docx\"");
    
  2. 修改后的完整代码示例

    • 流式返回版本:
      const rs = fs.createReadStream(fullPath);
      res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
      res.setHeader("Content-Disposition", "inline; filename=\"Sample-Document.docx\"");
      rs.pipe(res);
      
    • 读取文件后返回版本:
      const file = await fs.readFile(fullPath); // fs来自fs/promises
      res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
      res.setHeader("Content-Disposition", "inline; filename=\"Sample-Document.docx\"");
      res.status(200).send(file);
      
  3. 额外注意事项

    • 确保浏览器支持docx内联预览:Edge、Chrome等现代浏览器原生支持或可通过插件实现,老旧浏览器可能仍会触发下载
    • 检查是否存在其他强制下载的响应头:部分框架或中间件可能默认添加attachment类型的Content-Disposition,需确保覆盖或移除
    • 若使用iframe加载,需保证服务器配置了正确的CORS头(如果存在跨域场景),否则浏览器会限制文件加载

内容的提问来源于stack exchange,提问作者Grosu Cristi-Alexandru

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:40:53