SET PATH *LIBL ; 

CREATE OR REPLACE FUNCTION RESTAPI.MISC_UPLOAD_FILE ( 
	"DATA" CLOB(2147483647) ) 
	RETURNS CLOB(32768)   
	LANGUAGE SQL 
	SPECIFIC RESTAPI.MISC_UPLOAD_FILE 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DECRESULT = (31, 31, 00) , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *USER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE FILE_PATH VARCHAR ( 1056 ) ; 
DECLARE FILE_BLOB BLOB ( 2 G ) ; 
DECLARE TOKEN VARCHAR ( 128 ) ; 
DECLARE EXIT HANDLER FOR SQLEXCEPTION 
BEGIN 
RETURN 
JSON_OBJECT ( 
'success' : 'false' FORMAT JSON , 'error' : 'upload failed' , 
'filePath' : COALESCE ( FILE_PATH , '' ) , 'uploadToken' : COALESCE ( 
TOKEN , '' ) 
) ; 
END ; 
SELECT JT . FILEPATH , CAST ( BASE64_DECODE ( JT . FILE ) AS BLOB ( 2 G ) ) 
INTO FILE_PATH , FILE_BLOB 
FROM 
JSON_TABLE ( 
DATA , 
'$' 
COLUMNS ( 
FILEPATH VARCHAR ( 1056 ) PATH '$.filePath' , 
FILE CLOB ( 2 G ) PATH '$.file' 
) 
) JT ; 
SET TOKEN = BASE64_ENCODE ( VARCHAR ( GENERATE_UNIQUE ( ) ) ) ; 
IF FILE_PATH IS NULL 
OR FILE_PATH = '' THEN 
SET FILE_PATH = '/tmp/' || TOKEN ; 
END IF ; 
CALL IFS_WRITE_BINARY ( FILE_PATH , FILE_BLOB ) ; 
RETURN 
JSON_OBJECT ( 
'success' : 'true' FORMAT JSON , 'filePath' : FILE_PATH , 
'uploadToken' : TOKEN 
) ; 
END  ; 

GRANT ALTER , EXECUTE   
ON SPECIFIC FUNCTION RESTAPI.MISC_UPLOAD_FILE 
TO AMAPICS WITH GRANT OPTION ; 

GRANT EXECUTE   
ON SPECIFIC FUNCTION RESTAPI.MISC_UPLOAD_FILE 
TO PUBLIC ; 

