Sample code for 30+ languages & platforms
SQL Server

Get Contents of File as Base64

See more Encryption Examples

Demonstrates how to read the contents of a file and convert to a base64 string.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    DECLARE @bd int
    EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @bd, 'LoadFile', @success OUT, 'qa_data/jpg/starfish.jpg'
    IF @success = 0
      BEGIN

        PRINT 'Failed to load file.'
        EXEC @hr = sp_OADestroy @bd
        RETURN
      END

    EXEC sp_OAMethod @bd, 'GetEncoded', @sTmp0 OUT, 'base64'
    PRINT @sTmp0

    -- If you want mult-line base64:

    PRINT '--'
    EXEC sp_OAMethod @bd, 'GetEncoded', @sTmp0 OUT, 'base64_mime'
    PRINT @sTmp0

    -- If you want hex..

    PRINT '--'
    EXEC sp_OAMethod @bd, 'GetEncoded', @sTmp0 OUT, 'hex'
    PRINT @sTmp0

    -- etc.

    EXEC @hr = sp_OADestroy @bd


END
GO