后端接口返回二进制文件,前端 window.opent预览展示

详细步骤

1.修改 PreviewApi 函数:

  • 设置 responseType 为 'arraybuffer',以接收二进制数据。
javascript 复制代码
export const PreviewApi = (data) => request({
  method: 'post',
  url: '/dev-api/preview',
  responseType: 'arraybuffer',
  data
});

3.处理响应:

  • 使用 new Uint8Array(response.data) 将 ArrayBuffer 转换为 Uint8Array。
  • 使用 Blob 构造函数将 Uint8Array 转换为 Blob 对象。
  • 使用 URL.createObjectURL 方法生成 Blob URL。
  • 使用 window.open 方法在新窗口中打开生成的 Blob URL。
javascript 复制代码
<template>
  <div>
    <button @click="onPreview(row)">预览 PDF</button>
  </div>
</template>

<script>
import { ldjtPreviewApi } from '@/api/your-api-file'; // 引入你的 API 文件

export default {
  data() {
    return {
      row: { qqlsh: 'example_qqlsh' } // 示例数据,实际使用时从父组件或其他地方获取
    };
  },
  methods: {
    onPreview(row) {
      ldjtPreviewApi({ qqlsh: row.qqlsh }).then((response) => {
        if (response.status === 200) {
          const binaryData = new Uint8Array(response.data);
          const url = this.binaryToPdfUrl(binaryData);
          console.log('Generated URL:', url);
          window.open(url);
        } else {
          this.$message({
            message: '请求失败',
            type: 'error'
          });
        }
      }).catch((error) => {
        this.$message({
          message: error.message || '请求出错',
          type: 'error'
        });
      })
    },
    binaryToPdfUrl(binaryData) {
      const blob = new Blob([binaryData], { type: 'application/pdf' });
      const url = URL.createObjectURL(blob);
      return url;
    }
  }
};
</script>

<style scoped>
/* 你可以在这里添加一些样式 */
</style>

手动验证二进制数据

你可以将二进制数据保存为文件,手动打开验证 PDF 文件是否有效。以下是一个示例代码:

javascript 复制代码
function binaryToPdfFile(binaryData, filename) {
  const blob = new Blob([binaryData], { type: 'application/pdf' });

  // 创建一个临时的下载链接
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = filename;
  link.click();
}

// 调用函数,将二进制数据保存为 PDF 文件
binaryToPdfFile(new Uint8Array(response.data), 'test.pdf');
相关推荐
weixin-a1530030831612 分钟前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
ai小鬼头38 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim1 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim1 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
aha-凯心2 小时前
vben 之 axios 封装
前端·javascript·学习
遗憾随她而去.2 小时前
uniapp 中使用路由导航守卫,进行登录鉴权
前端·uni-app
xjt_09012 小时前
浅析Web存储系统
前端
foxhuli2293 小时前
禁止ifrmare标签上的文件,实现自动下载功能,并且隐藏工具栏
前端
青皮桔3 小时前
CSS实现百分比水柱图
前端·css