SQL Server
SQL Server
REST Download Binary File to Memory
See more REST Examples
Download a binary file to a Chilkat BinData object.Chilkat SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
DECLARE @iTmp0 int
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
-- This requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
DECLARE @rest int
EXEC @hr = sp_OACreate 'Chilkat.Rest', @rest OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- We're going to download a sample MS-Word doc file.
-- The URLs of our MS-Word sample documents are:
-- https://www.chilkatdownload.com/sample_data/sample.doc
-- https://www.chilkatdownload.com/sample_data/sample.docx
DECLARE @pathPartOfUrl nvarchar(4000)
SELECT @pathPartOfUrl = '/sample_data/sample.doc'
DECLARE @domain nvarchar(4000)
SELECT @domain = 'chilkatdownload.com'
DECLARE @bTls int
SELECT @bTls = 1
DECLARE @port int
SELECT @port = 443
DECLARE @bAutoReconnect int
SELECT @bAutoReconnect = 1
EXEC sp_OAMethod @rest, 'Connect', @success OUT, @domain, @port, @bTls, @bAutoReconnect
IF @success <> 1
BEGIN
EXEC sp_OAGetProperty @rest, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @rest
RETURN
END
DECLARE @bd int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT
EXEC sp_OAMethod @rest, 'FullRequestNoBodyBd', @success OUT, 'GET', @pathPartOfUrl, @bd
IF @success <> 1
BEGIN
EXEC sp_OAGetProperty @rest, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @rest
EXEC @hr = sp_OADestroy @bd
RETURN
END
-- A 200 response is expected for actual success.
-- If we don't get a 200 response, then the response body was not actually
-- the file data, but it was text containing error information.
EXEC sp_OAGetProperty @rest, 'ResponseStatusCode', @iTmp0 OUT
IF @iTmp0 <> 200
BEGIN
DECLARE @sbErrorText int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbErrorText OUT
EXEC sp_OAMethod @sbErrorText, 'AppendBd', @success OUT, @bd, 'utf-8', 0, 0
EXEC sp_OAMethod @sbErrorText, 'GetAsString', @sTmp0 OUT
PRINT @sTmp0
PRINT '-- Failed.'
EXEC @hr = sp_OADestroy @rest
EXEC @hr = sp_OADestroy @bd
EXEC @hr = sp_OADestroy @sbErrorText
RETURN
END
-- Save to a local file.
-- Change the file path based on your operating system or needs...
EXEC sp_OAMethod @bd, 'WriteFile', @success OUT, 'c:/temp/qa_output/sample.doc'
IF @success <> 1
BEGIN
PRINT 'Failed to save to local file.'
EXEC @hr = sp_OADestroy @rest
EXEC @hr = sp_OADestroy @bd
EXEC @hr = sp_OADestroy @sbErrorText
RETURN
END
PRINT 'REST Download of MS-Word File was successful.'
EXEC @hr = sp_OADestroy @rest
EXEC @hr = sp_OADestroy @bd
EXEC @hr = sp_OADestroy @sbErrorText
END
GO