c#:从Web Service返回的byte[]在新选项卡中显示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>

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);
}
});
}

web服务方法:

[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方法,如果我直接运行web服务,我可以在新选项卡中打开PDF。来自visual studio。然而,如果我通过我已经实现的web界面来做,什么也不会发生。所以我认为我可能需要返回HttpContext.Current.Response,我试图记录它,看看数据中有什么,我收到了不可读的数据。

我应该如何显示PDF从byte[]从web服务?我需要为我的web服务做些什么来提供结果文件?

方法2:返回byte[]数据到ajax调用,并使用以下方法:

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

如果这样做,PDF文件就不能正常打开,好像它被损坏了

不需要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服务,它就会奇迹般地工作。

相关内容

最新更新