自在猫先生 2023-12-13 09:43 采纳率: 62.9%
浏览 1
已结题

React18.2+antd+4.74.2文档打开预览乱码无法打开

我编写了一个功能,打开我生成的文档,在前端点击预览调用接口的时候打开文档乱码了并且无法打开无法正常显示文档信息。
前端环境:react版本18.2,antd
后端环境:.NET 4.7.2框架MVC架构模式
部分前端代码如下:


  const columns = [
        {
          title: '客户编号',
          dataIndex: 'CustomerID',
          key: 'CustomerID',  
        },
          {
            title: '文档名称',
            dataIndex: 'FileName',
            key: 'FileName',
            ellipsis: true, // 使用ellipsis属性
            render: (text) => (
              <span>{text}</span>
            ),
          },
          {
              title: '编辑',
              key: 'edit',
              render: (text,record) => (
                <Button type='primary' onClick={() => handleEdit(record)}>编辑</Button>
              ),
            },
            {
              title: '预览',
              key: 'Preview',
              render: (text,record) => (
                <Button type='primary' onClick={() => handlePreview(record)}>预览</Button>
              ),
            },
            {
              title: '删除',
              key: 'del',
              render: (text,record) => (
                <Button type='primary' danger onClick={() => deldoument(record.CustomerID)}>删除</Button>
              ),
            },
      ];
  
 const handlePreview = async (record) => {
        setSelectedDocument(record); // 设置选中的文档
      
        try {
          const options = {
            method: 'POST', // 根据实际情况修改请求方法
            url: '/AxMetadata/PreviewDocument', // 根据实际情况填写接口地址
            responseType: 'blob', // 响应类型为blob
            headers: {
              'Content-Type': 'application/json',
            },
            data: record, // 传递选中的文档数据给后端接口
          };
          const response = await axios(options);
          const fileBlob = new Blob([response.data], { type: 'application/pdf' });
          const fileURL = URL.createObjectURL(fileBlob);
      
          // 创建一个隐藏的object元素用于展示文档预览
          const objectElement = document.createElement('object');
          objectElement.data = fileURL;
          objectElement.type = 'application/pdf';
          objectElement.width = '100%';
          objectElement.height = '600px';
          document.body.appendChild(objectElement);
        } catch (error) {
          console.error(error);
        }
      
        setSelectedDocument(null); // 清空选中的文档
      };

 <Table
            className="custom-table"
                dataSource={dataSource}
                columns={columns}
                onRow={(record) => {
                  return {
                    onClick: () => setSelectedData(record), // 点击行时,设置选中的数据
                  };
                }}
                
            />

部分后端代码如下:

 public ActionResult PreviewDocument(Document document)
        {
            try
            {
               var response= _IDocumentInterOp.PreviewDocument(document);
                return new FileContentResult(response.Content.ReadAsByteArrayAsync().Result, "application/pdf");
            }
            catch (Exception ex)
            {

                // 使用 log4net 记录异常信息
                log.Error(ex.Message, ex);

                // 返回一个错误视图或者其他处理方式,这取决于你的需求
                return View("Error");
            }
        }

 public HttpResponseMessage PreviewDocument(Document document)
        {
            string folderPath = string.Empty;
            try
            {
                using (var connection = _ICreateSqlConnection.CreateSqlConnection())
                {

                    connection.Open();
                    string query = "select FilePath from Customer_EvironmentConfig where CustomerID=@CustomerID";

                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@CustomerID", document.CustomerID);
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                folderPath = reader["FilePath"].ToString();
                            }
                            // 关闭第一个数据读取器
                            reader.Close();
                        }
                    }

                }
                // 根据实际情况处理文档预览操作
                var filePath = Path.Combine(@"C:\", folderPath, document.FileName);
                var fileBytes = File.ReadAllBytes(filePath);
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                var content = new ByteArrayContent(fileBytes);
                content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = document.FileName
                };
                response.Content = content;
                return response;
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR PreviewDocument Document opening exception, please carefully check the code", ex);
            }
        }

乱码信息如下

img

img

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 12月21日
    • 创建了问题 12月13日

    悬赏问题

    • ¥15 上传图片时提交的存储类型
    • ¥15 Ubuntu开机显示器只显示kernel,是没操作系统(相关搜索:显卡驱动)
    • ¥15 VB.NET如何绘制倾斜的椭圆
    • ¥15 在rhel8中安装qemu-kvm时遇到“cannot initialize crypto:unable to initialize gcrypt“报错”
    • ¥15 arbotix没有/cmd_vel话题
    • ¥15 paddle库安装时报错提示需要安装common、dual等库,安装了上面的库以后还是显示报错未安装,要怎么办呀?
    • ¥20 找能定制Python脚本的
    • ¥15 odoo17的分包重新供应路线如何设置?可从销售订单中实时直接触发采购订单或相关单据
    • ¥15 用C语言怎么判断字符串的输入是否符合设定?
    • ¥15 通信专业本科生论文选这两个哪个方向好研究呀