Create Procedure sp_Upload(@path Varchar(200))
As
Begin
Set NoCount on
/*
Create Table myFile
(
ID int Identity(1,1),
filename Varchar(100),
files Varbinary(max)
)
*/
Declare @Cmd nVarchar(400)
Declare @ID int
Declare @filename Varchar(100)
Declare @files VarBinary(max)
Declare @result Int
Truncate Table myFile
if (Right(@path,1)<>'\')
Set @path=@path+'\'
Set @Cmd='dir /b '+@path
Insert Into myFile(filename) 
Exec master..xp_cmdshell @Cmd
DECLARE Cur CURSOR FOR 
Select ID,filename From myFile Where filename is not null

OPEN Cur
FETCH NEXT FROM Cur INTO @ID,@filename
WHILE @@FETCH_STATUS = 0
BEGIN
Set @Cmd='Select @files=bulkColumn From openrowset(Bulk '''+@path+@filename+''',Single_Blob) as a'
Begin Try
Exec sp_executesql @Cmd,N'@files VarBinary(max) out',@files out
End Try
Begin Catch
Print ERROR_MESSAGE()
End Catch
Update myFile Set files=@files Where ID=@ID
FETCH NEXT FROM Cur INTO @ID,@filename
END 
CLOSE Cur
DEALLOCATE Cur

Select * From myFile
End



Create Procedure sp_Download(@path Varchar(2000))
As
Begin
Declare @App int
Declare @ID int
Declare @result int
Declare @filename Varchar(100)
Declare @files VarBinary(max)
Declare @fielpath Varchar(400)
if (Right(@path,1)<>'\')
Set @path=@path+'\'
DECLARE Cur CURSOR FOR 
Select ID,filename,files From myFile Where filename is not null

OPEN Cur
FETCH NEXT FROM Cur INTO @ID,@filename,@files

WHILE @@FETCH_STATUS = 0
BEGIN
Set @fielpath=@path+@filename
Exec sp_OACreate 'ADODB.Stream', @App OUT
Exec sp_OASetProperty @App, 'Mode', 3
Exec sp_OASetProperty @App, 'Type', 1
EXEC sp_OAMethod @App,'Open'
Exec sp_OAMethod @App, 'Write',null,@files
Exec sp_OAMethod @App, 'SaveToFile',null,@fielpath,2
Exec sp_OADestroy @App
FETCH NEXT FROM Cur INTO @ID,@filename,@files
End
CLOSE Cur
DEALLOCATE Cur
End