内联基础64可以很好地处理图像(只要图像很小),因此您可能处在正确的轨道上。但是,我认为您没有为PDF或大多数其他Blob(varbinary(max)
在sql Server中)找到正确的路径。
我这样做的方法是创建一个HTTP处理程序(Controller,ASHX,ASPX等),该处理程序设置正确的HTTP标头并将从sql Server检索到的数据Response.BinaryWrite()
作为字节数组传递。这是快速,清洁和可靠的。它也需要很少的代码。
相比之下,base 64编码会增加文件大小,并且我不知道有任何可靠的方法来处理base 64字符串客户端并指示浏览器使用正确的应用程序打开它。另外,编码/解码完全是不必要的开销(这在大文件上可能很重要)。
顺便说一句,您也可以对图像使用HTTP处理程序。或者,您可以继续使用base 64,但将所有图像放在一个JSON对象中,这将减少请求数量(以更多的客户端处理代码为代价)。
我将一些生产代码分解为仅处理PDF的部分。 这应该进行最少的修改。
首先将通用处理程序添加到Visual Studio中的项目。它将具有ASHX扩展名。
public partial class RequestHandler : IHttpHandler
{
public void ProcessRequest( HttpContext context ) {
HttpRequest request = context.Request;
HttpResponse response = context.Response;
byte[] bytes = null; // get from your database
string fileName = null; // get from database or put something generic here like "file.pdf"
response.ContentType = "application/pdf";
response.addheader( "content-disposition", "inline;filename=" + fileName );
response.addheader( "Content-Length", bytes.Length.ToString() );
response.Buffer = true;
response.BinaryWrite( bytes );
response.Flush();
}
public bool IsReusable {
get {
return true;
}
}
}
要调用此代码,您可以简单地链接到它,例如<a href="RequestHandler.ashx?id=abc">Download</a>
。您还可以将该代码放入ASPX页面中,并在按钮单击,页面事件等情况下触发它。