我编写了一个功能,打开我生成的文档,在前端点击预览调用接口的时候打开文档乱码了并且无法打开无法正常显示文档信息。
前端环境: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);
}
}
乱码信息如下