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

telerik:RadGrid二进制文件数据列无法正常加载如何解决

问题原因

你当前使用GridBoundColumn绑定二进制字段时,默认会调用字段值的ToString()方法,字节数组的ToString()返回固定值System.Byte[],所以无法展示实际内容,需要根据你要呈现的二进制内容类型选择对应解决方案:

方案1:二进制为文件(文档/图片等),需提供下载/预览功能

替换GridBoundColumn为GridTemplateColumn,自定义列内交互逻辑:

前端代码

<telerik:GridTemplateColumn HeaderText="Ficheiro" UniqueName="FileContent">
    <ItemTemplate>
        <!-- 下载按钮 -->
        <asp:LinkButton ID="btnDownload" runat="server" Text="下载文件" 
            CommandName="DownloadFile" 
            CommandArgument='<%# Eval("你的文件主键字段名") %>' />
        <!-- 如果是图片可直接预览,需配套实现通用文件读取接口 -->
        <!-- <img src="FileReadHandler.ashx?id=<%# Eval("你的文件主键字段名") %>" alt="预览" width="100" /> -->
    </ItemTemplate>
</telerik:GridTemplateColumn>

后端下载逻辑(RadGrid的ItemCommand事件中处理)

protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
    if (e.CommandName == "DownloadFile")
    {
        int fileId = Convert.ToInt32(e.CommandArgument);
        // 替换为你自己的数据库查询逻辑,获取对应文件的字节数组、文件名、Content-Type
        byte[] fileBytes = QueryFileContentById(fileId);
        string fileName = QueryFileNameById(fileId);
        string contentType = QueryFileContentTypeById(fileId);

        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = contentType;
        Response.AddHeader("Content-Disposition", $"attachment;filename={HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)}");
        Response.BinaryWrite(fileBytes);
        Response.Flush();
        Response.End();
    }
}

方案2:二进制为文本内容,需直接展示字符串

如果FileContent字段存储的是编码后的文本,可在数据绑定时做字节转字符串处理,推荐用ItemDataBound事件实现更稳定:

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem dataItem = (GridDataItem)e.Item;
        byte[] contentBytes = (byte[])DataBinder.Eval(dataItem.DataItem, "FileContent");
        // 替换为你实际用的编码格式(UTF8/GB2312等)
        string contentStr = System.Text.Encoding.UTF8.GetString(contentBytes);
        // 可以按需做内容截断,避免撑破单元格
        dataItem["FileContent"].Text = contentStr.Length > 50 ? contentStr.Substring(0,50) + "..." : contentStr;
    }
}

注意事项

  • 不建议直接在GridBoundColumn的DataFormatString中做转换,编码异常时容易导致整个页面报错
  • 存储二进制文件时建议同步存储文件扩展名、Content-Type、文件大小等元数据,后续业务处理更灵活

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:15:08