【发布时间】:2021-10-21 10:28:57
【问题描述】:
当用户单击图标链接时,我的应用程序正在尝试显示存储在数据库中的 PDF。
当链接被点击时,它会触发一个对 Web 服务的 Ajax 调用,该服务使用 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>
Ajax 调用:
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 文件无法正常打开,就像它已损坏一样
【问题讨论】:
-
忽略所有 Web 服务内容,如果您只是将 PDF 文件从磁盘读取到
byte[]中,您将如何显示它?您的程序如何显示任何内容?它是 Web 应用程序、Windows 窗体应用程序还是其他什么? -
@NetMage 它是一个使用网络表单的网络应用程序。我知道如何将 pdf 文件保存到本地磁盘或直接从 Web 服务打开它,但我需要在浏览器选项卡上显示它,这就是重点。
-
那么你需要将
byte[]作为pdf文件返回给浏览器:见this answer。 -
@NetMage 的答案是针对 Asp.MVC,而不是针对 Asp.Net webform。
-
抱歉,已修复为网络表单版本。
标签: javascript c# asp.net pdf webforms