Example: upload a file in a multipart request

Shows an example of a method you might use from a client to upload an image along with other data in a function using a form-data type HTTP multipart request.

Example multipart request

IMPORT os
IMPORT com

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

PUBLIC FUNCTION FetchFiles(
    id INTEGER,
    image STRING ATTRIBUTE(WSMedia="image/*"),
    submit STRING)
  ATTRIBUTES (WSPost,
              WSPath="/files/fetch",
              WSDescription="upload image file to the server",
              WSThrows="400:@myerror")
  RETURNS STRING ATTRIBUTE(WSMedia="text/html")
    DEFINE ret STRING
    DEFINE ok INTEGER
    IF id == 0 THEN
        LET myerror.code=999
        LET myerror.reason="I don't like ID of 0"
        CALL com.WebServiceEngine.SetRestError(400,myerror)
    ELSE
        DISPLAY "Got image at ",image
        LET ok = os.Path.DELETE("myimage.png")
        LET ok = os.Path.RENAME(IMAGE,"myimage.png")
        LET ret = SFMT("<HTML><body><h1>Got image with ID %1</h1></body></HTML>",id)
    END IF
    RETURN ret
END FUNCTION

The image file format is specified via the WSMedia attribute. The attachment is handled through the STRING data type and WSMedia attribute.

The "FetchFiles" function needs to be called through an HTML form for the user to select the file to upload. The form needs to have two input fields and one submit button, according to the function parameters.
  1. Create the form from the code sample. Remember to change the action tag value to the URL of your server.
  2. Save as, for example, upload.htmlon the client side.
  3. Open the file locally in a browser to upload a file. Ensure the service is running.
!DOCTYPE html>
<html>
   <FORM NAME="upload" method="post" action="http://localhost:8090/Myservice/files/fetch" enctype='multipart/form-data'>
    <div>
        <label for="name">ID:</label>
        <input type="text" name="id"/>
    </div>
    <div>
        <label>picture:</label>
        <input type="file" name="image" accept="image/png, image/jpeg" />
    </div>
    
    <input type="submit" name="submit" value="Send"/>
    
    </FORM>
</html>

In the output you see that the image is sent in parts that are combined into one or more sets of data in the body. Parts are separated by boundaries, the

---------------------------70482736912266

string in the output example.

On successfully receiving the file, the server returns the message to display in the browser. Otherwise, an error is returned and displayed.
Figure: Sample output of multipart HTTP request

Sample output of multipart HTTP request