Download a file as an attachment to a response

This example demonstrates how to return a file as an attachment using the WSAttachment attribute

In order to return a file as an attachment to a client, set the WSAttachment attribute on an output parameter.

Example 1: downloading file using WSAttachment

In this example:
  • A STRING type is defined with a WSAttachment attribute.
  • A WSMedia attribute is added to handle the data format for images.
IMPORT com
IMPORT os

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

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

    LET fname="favicon.ico"
    LET ok = os.Path.exists(fname)
    IF ok THEN
        LET ret = fname
    ELSE
      LET myerror.reason = SFMT("File (%1) does not exist", fname)
      CALL com.WebServiceEngine.SetRestError(400,myerror)
    END IF
  RETURN ret
END FUNCTION
Figure: Output of HTTP response to download image file


In Figure 1 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.