Example: upload a file as attachment in request body

Shows a sample function uploading an image file as attachment in the message request body.

In order to send a file as an attachment to the Web service, set the WSAttachment attribute on an input parameter.

Example 1: upload file as attachment using WSAttachment

In this example:
  • "fname" is defined as type STRING with a WSAttachment atrribute.
  • The WSMedia attribute handles the data format for images.
The GWS stores the file in a temporary directory, and returns the absolute path to the file in the input parameter ("fname"). When the call to the function ends, the file will be removed unless it is saved to a location on disk. The os.Path.rename instruction moves the file from the temporary directory to the current directory.
IMPORT os

PUBLIC FUNCTION UploadFile( fname STRING ATTRIBUTES(WSAttachment, WSMedia="image/*") )
  ATTRIBUTES (WSPost,
              WSPath="/files2/fetch")
  RETURNS STRING ATTRIBUTE(WSMedia="text/plain")
    DEFINE ret, new_fname STRING
    DEFINE ok INTEGER
    LET new_fname = os.Path.pwd()||os.Path.separator()||new_fname
    LET ok = os.Path.rename(fname,new_fname)
    LET ret = SFMT("Got image: %1",new_fname)
    RETURN ret
END FUNCTION
Figure: Output of HTTP request to upload file


In Figure 1 the image is sent as an attachment in the message body.