0

I have a situation where I have PDF files stored in a database as Base64 data in VARCHAR(MAX) columns. These are accessed from an ASP.NET Core MVC app. Users need to be able to view and download these files in a browser. Currently, we return the data as a string from a query, use Convert.FromBase64String() and return the converted byte[] as FileContentResult.

The problem is some files are very large, and are causing timeout issues when converting to a byte array. I would prefer to be able to stream the result back to users as it's being decoded instead of having to do it all up front, but I'm not sure how. Would it be possible to somehow decode the Base64 string in chunks and stream it back as FileStreamResult instead?

Valuator
  • 3,262
  • 2
  • 29
  • 53
  • @JeroenMostert perhaps. Could I decode the string in chunks and write the bytes directly to the response Body? – Valuator Oct 20 '20 at 21:50
  • You can stream data from a `VARCHAR(MAX)` column by using [`SqlDataReader.GetStream`](https://learn.microsoft.com/dotnet/api/system.data.sqlclient.sqldatareader.getstream) (or `.GetTextReader`). There is no need to chunk it yourself. The drawback to this is that you will tie up a connection to SQL Server for as long as your client needs to read the response (which can be quite long, on a slow connection). In that case you may well be better off using `FILESTREAM` on the server end rather than strings, as it's optimized for such scenarios. – Jeroen Mostert Oct 20 '20 at 21:52
  • Yeah I don't think we want to tie up the SQL connection like that. Want to still load the entire Base64 string to the app server and stream it to the client as it decodes. – Valuator Oct 20 '20 at 22:07
  • That's a lot more annoying then, as there is no direct way to produce a `Stream` from a `String` either (which the solution with `CryptoStream` requires). Of course [we do have a question for that one as well](https://stackoverflow.com/q/1879395/4137916), but (almost) all the answers there are quite inefficient in that they make a redundant copy of the data. – Jeroen Mostert Oct 20 '20 at 22:15

0 Answers0