Today I have been experimenting with SQL binary objects. I started by storing an image in a table, making an AJAX request for a base64 encoding of the image, and displaying it with.
<img src="data:image/jpeg;base64,' + base64imageReturnedWithAjax + '">')
The image displays fine.
The web project I'm working on also requires file downloads (PDF, mainly) - great, I thought, I'll store the PDF as a SQL binary object too, collect it from the server in the same way and then somehow magically decode it for download at the other end.
Help!
I first tried to decode it using a jQuery base64 decoder (https://github.com/carlo/jquery-base64) with:
$.base64.decode(base64fileReturnedWithAjax)
This generates the following error in the console:
Uncaught Cannot decode base64
_getbyte64
_decode
$.ajax.success
f.Callbacks.o
f.Callbacks.p.fireWith
w
f.support.ajax.f.ajaxTransport.send.d
My question is, therefore: Is this a feasible way to handle file downloads? if so, how! and if not, is there an advised way to allow a file to be downloaded from a SQL table?
Kind regards, ATfPT
EDIT: If it helps, this is the webmethod that retrieves and sends the file from the db/server (in VB.NET). Fileblob is the binary object within the database.
'Having connected to the table
While lrd.Read()
Dim fileBytes = CType(lrd("Fileblob"), Byte())
Dim stream = New MemoryStream(fileBytes, 0, fileBytes.Length)
Dim base64String = Convert.ToBase64String(stream.ToArray())
document.Add(base64String)
End While
Dim serializer As New JavaScriptSerializer()
Dim returnVal As String = serializer.Serialize(document)
Return returnVal
Inline base 64 works well with images (as long as they are small), so you are probably on the right track there. However, I don't think you are going down the right path for PDFs or most other blobs (varbinary(max) in SQL Server).
The way I would do this is to create a HTTP handler (Controller, ASHX, ASPX, etc.) which sets the correct HTTP headers and passes the data retrieved from SQL Server to Response.BinaryWrite() as a byte array. This is fast, clean, and reliable. It also requires very little code.
By comparison, base 64 encoding increases file size, and I'm not aware of any reliable means to process a base 64 string client-side and instruct the browser to open it with the correct application. Plus, the encoding/decoding is completely unnecessary overhead (which may be significant on a large file).
Incidentally, you could also use a HTTP handler for your images. Or, you could continue you use base 64 but serve all your images in a single JSON object which would reduce your request count (at the expense of more client-processing code).
I stripped down some production code into just the part which handles PDFs. This should work with minimal modification.
Start by adding a Generic Handler to your project in Visual Studio. It will have an ASHX extension.
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;
}
}
}
To invoke this code, you can simply link to it e.g. <a href="RequestHandler.ashx?id=abc">Download</a>. You can also put this code inside an ASPX page and trigger it in response to a button click, page event, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With