Example: download a file in response body

Shows two sample functions; one returning a file as an attachment, and another example returning a file in the message response body.

Example 1: downloading file using WSAttachment

IMPORT com
IMPORT os

PUBLIC DEFINE myerror RECORD ATTRIBUTE(WSError="My error")
  code    INTEGER,
  reason  STRING
END RECORD

FUNCTION downloadImageFile()
  ATTRIBUTES (WSGet, WSPath="/files3/down",
              WSDescription="download image file to the client as attachment with WSAttachment",
              WSThrows="400:myerror")
  RETURNS (STRING ATTRIBUTE(WSAttachment, WSMedia="image/*") )
    DEFINE ret, fn STRING
    DEFINE ok INTEGER

    LET fn="favicon.ico"
    LET ok = os.Path.exists(fn)
    IF ok THEN
        LET ret = fn
    ELSE
      LET myerror.reason = SFMT("File (%1) does not exist", fn)
      CALL com.WebServiceEngine.SetRestError(400,myerror)
    END IF
  RETURN ret
END FUNCTION
In order to send a file as an attachment, your function must have one output parameter only. In the sample function, a STRING type is defined with a WSAttachment attribute. A WSMedia attribute is added to handle the data format for images.
The Content-Disposition response header in the output indicates that the content is expected as an attachment. Therefore, when the function is called, the file is downloaded and saved to the client locally in its TMP directory.
Figure: Output of HTTP response with image file


Example 2: downloading file without WSAttachment

PUBLIC FUNCTION help3()
  ATTRIBUTES (WSGet,
              WSDescription="download text file to the client without WSAttachment",
              WSPath="/help/file3")
  RETURNS ( INTEGER ATTRIBUTE(WSHeader), TEXT )
    DEFINE t TEXT
    LOCATE t IN MEMORY
    CALL t.readFile("file3.txt")
    RETURN 3, t
END FUNCTION

In this example the help3 function returns a text file. The content is transferred as text in the message body as shown in the output. Data of integer type is transferred in a response header.

Figure: Output of HTTP response

Sample output of HTTP response sending a file in the body

In the output the header is given the default name, "rv0", at runtime. You can change default header naming via the WSName attribute, for example with:

RETURNS (INTEGER ATTRIBUTE(WSHeader, WSName="MyHeader"), TEXT)