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: downloading file using WSAttachment

In this sample REST function a file is returned as attachment. The function has one return parameter:
  • A return paramater is defined as STRING type with a WSAttachment attribute. The REST engine treats the parameter value as a path to a file to be attached.
  • A WSMedia attribute is added to handle the data format for images. The wildcard (image/*) in WSMedia allows for all image types. If the file can be any type, WSMedia is not specified with WSAttachment.

The format is chosen according to that specified in the Accept or Content-Type headers. You code in your function to replace the image/* placeholder in the Accept or Content-Type header with the actual value. This can also be done using the WSContext attribute to set the header.

WSThrows – is set to handle errors. If the file does not exist, the WSError attributed variable is set with a description of the error and the SetRestError() method is called to return it.
IMPORT com
IMPORT os

PUBLIC DEFINE userError RECORD ATTRIBUTES(WSError = "User error")
  message STRING
END RECORD

PUBLIC FUNCTION downloadImageFile()
  ATTRIBUTES (WSGet, 
              WSPath = "/files3/images",
              WSDescription = "download image file to the client with WSAttachment",
              WSThrows = "400:@userError")
  RETURNS (STRING ATTRIBUTES(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 userError.message = SFMT("File (%1) does not exist", fname)
      CALL com.WebServiceEngine.SetRestError(400,userError)
    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.