首页 > 解决方案 > C#:从 Web 服务返回的字节 [] 在新选项卡中显示 PDF

问题描述

当用户单击图标链接时,我的应用程序正在尝试显示存储在数据库中的 PDF。

单击链接时,它将触发对 Web 服务的 Ajax 调用,该 Web 服务使用 ID 检索 byte[] 数组中的 PDF 数据。

html组件:

    <a href="#" onclick="getSPOD(<%=TransportationDocument != null ? TransportationDocument.BusinessID.ToString() : String.Empty %>);return false;">
        <img alt="SPOD" src="images/icons/adobe_acrobat_icon.png">
    </a>

阿贾克斯调用:

function getSPOD(id) {
    $.ajax({
        type: "GET",
        url: `Services/MyService.asmx/RetrieveSPODData?id='${id}'`,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            console.log(data);
        },
        error: function (textStatus, errorThrown) {
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
}

网络服务方法:

[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[WebMethod]
public HttpResponse RetrieveSPODData(string id)
{
    string query = @"Select * from dcmnts 
                         where BUSNSS_ID = :BUSNSS_ID";
    DataTable dataTable = new DataTable();
    OracleCommand command = null;
    OracleDataAdapter adapter = null;

    string ConnString = ConfigurationManager.ConnectionStrings["DbConnEnc"].ToString();

    byte[] data = null;
    using (OracleConnection connection = new OracleConnection(BaseEncryptor.DecryptString(ConnString)))
    {
        try
        {
            if (connection.State != ConnectionState.Open)
                connection.Open();
            command = new OracleCommand(query, connection);
            command.Parameters.Add(new OracleParameter("BUSNSS_ID", id));
            adapter = new OracleDataAdapter(command);

            adapter.Fill(dataTable);
            foreach (DataRow row in dataTable.AsEnumerable())
            {
                data = row.Field<byte[]>("SUMMARY_SPOD");
            }
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.BinaryWrite(data);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();

            return HttpContext.Current.Response;
        }
        finally
        {
            if (adapter != null) { adapter.Dispose(); adapter = null; }
            if (command != null) { command.Dispose(); command = null; }
        }
    }
}

在语法方面,没有问题。但是,我不知道如何从那里显示 pdf。通过使用HttpContext.Current.Response方法,如果我直接从 Visual Studio运行 Web 服务,我可以在新选项卡中打开 PDF。但是,如果我通过我已实现的 Web 界面进行操作,则什么也没有发生。所以我虽然可能需要返回HttpContext.Current.Response,但我尝试记录它以查看数据中的内容,但我收到了不可读的数据。

我应该如何显示来自网络服务的 byte[] 的 PDF?我需要做什么才能让我的 Web 服务提供结果文件?

方法2:将byte[]数据返回给ajax调用,使用如下:

var file = new Blob([data.d], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);

通过这样做,PDF文件无法正常打开,就好像它已损坏一样

标签: javascriptc#asp.netpdfwebforms

解决方案


不需要 AJAX:

    <a href="Services/ProofOfDeliveryData.asmx/RetrieveSPODData?id=<%=TransportationDocument != null ? TransportationDocument.BusinessID.ToString() : String.Empty %>" Target="_blank">
        <img alt="SPOD" src="images/icons/adobe_acrobat_icon.png">
    </a>

只需使链接直接转到 Web 服务,它就可以正常工作。


推荐阅读