Module : mime

Module Overview

This module provides functions to encapsulate multiple body parts, such as attachments in a single message. The communication of such messages follow the MIME (Multipurpose Internet Mail Extensions) specification as specified in the RFC 2045 standard.

Entity refers to the header fields and the content of a message, or a part of the body in a multipart entity.

Modify and retrieve the data in an entity

The module provides functions to set and get an entity body from different kinds of message types, such as XML, text, JSON, blob, and body parts. Headers can be modified through functions such as addHeader(), setHeader(), removeHeader(), etc.

Samples

Handle multipart request

The sample service given below handles a multipart request. It extracts the body content from each part, converts it to a string, and sends a response.

import ballerina/http;
import ballerina/log;
import ballerina/mime;

@http:ServiceConfig {
    basePath: "/test"
}
service test on new http:Listener(9090) {

    @http:ResourceConfig {
        methods: ["POST"],
        path: "/multipleparts"
    }
    // The resource that handles multipart requests.
    resource function multipartResource(http:Caller caller, http:Request request) {
        http:Response response = new;

        // Get the body parts from the request.
        var bodyParts = request.getBodyParts();
        if (bodyParts is mime:Entity[]) {
            string content = "";
            // Iterate through each body part and handle the content.
            foreach var part in bodyParts {
                content = content + " -- " + handleContent(part);
            }
            response.setPayload(<@untainted> content);
        } else {
            // If there is an error while getting the body parts, set the 
            // response code as 500 and set the error message as the 
            // response message.
            response.statusCode = 500;
            response.setPayload(<@untainted> bodyParts.reason());
        }

        var result = caller->respond(response);
        if (result is error) {
            log:printError("Error in responding", err = result);
        }
    }
}

// The function that handles the content based on the body part type.
function handleContent(mime:Entity bodyPart) returns @tainted string {
    var mediaType = mime:getMediaType(bodyPart.getContentType());
    if (mediaType is mime:MediaType) {
        // Get the base type of the specific body part.
        string baseType = mediaType.getBaseType();
        // If the base type is ‘application/xml’ or ‘text/xml’, get the XML 
        // content from body part.
        if (mime:APPLICATION_XML == baseType || mime:TEXT_XML == baseType) {
            var payload = bodyPart.getXml();
            if (payload is xml) {
                return payload.getTextValue();
            } else {
                return "Error in parsing xml payload";
            }
        } else if (mime:APPLICATION_JSON == baseType) {
            // If the base type is ‘application/json’, get the JSON content 
            // from body part.
            var payload = bodyPart.getJson();
            if (payload is json) {
                return payload.toJsonString();
            } else {
                return "Error in parsing json payload";
            }
        }
    } else {
        return mediaType.reason();
    }
    return "";
}

The sample request that is sent to the above service is shown below.

curl -v -F "request={\"param1\": \"value1\"};type=application/json" -F "language=ballerina;type=text/plain" -F "upload=@/home/path-to-file/encode.txt;type=application/octet-stream"  http://localhost:9090/test/multipleparts -H "Expect:"

Create a multipart request

Following code snippet creates a multipart request. It includes two body parts with application/json and application/xml content type.

// Create a JSON body part.
mime:Entity bodyPart1 = new;
// Set the JSON content.
bodyPart1.setJson({"bodyPart": "jsonPart"});

// Create another body part using an XML file.
mime:Entity bodyPart2 = new;
bodyPart2.setFileAsEntityBody("ballerina/mime/file.xml", contentType = mime:APPLICATION_XML);

//Create an array to hold all the body parts.
mime:Entity[] bodyParts = [bodyPart1, bodyPart2];

// Set the body parts to the outbound response.
http:Request outRequest = new;
// Set the content type as ‘multipart/mixed’ and set the body parts.
outRequest.setBodyParts(bodyParts, contentType = mime:MULTIPART_MIXED);

Records

Detail Holds the details of entity header and body related errors.

Objects

ContentDisposition

Represents values in Content-Disposition header.

Entity

Represents the headers and body of a message. This can be used to represent both the entity of a top level message and an entity(body part) inside of a multipart entity.

MediaType

Describes the nature of the data in the body of a MIME entity.

Functions

base64Decode

Deprecated API. Decodes a given input with MIME specific Base64 encoding scheme.

base64DecodeBlob

Deprecated API. Decodes a given byte[] with Base64 encoding scheme.

base64Encode

Deprecated API. Encodes a given input with MIME specific Base64 encoding scheme.

base64EncodeBlob

Deprecated API. Encodes a given byte[] with Base64 encoding scheme.

getContentDispositionObject

Given the Content-Disposition as a string, gets the ContentDisposition object with it.

getMediaType

Given the Content-Type in string, gets the MediaType object populated with it.

prepareDecodingErrorWithDetail

Constructs a DecodeError with the given details.

prepareEncodingErrorWithDetail

Constructs an EncodeError with the given details.

Constants

APPLICATION_OCTET_STREAM

Represent application/octet-stream media type.

APPLICATION_JSON

Represent application/json media type.

APPLICATION_XML

Represent application/xml media type.

APPLICATION_SVG_XML

Represent application/svg+xml media type.

APPLICATION_XHTML_XML

Represent application/xhtml+xml media type.

APPLICATION_SOAP_XML

Represent application/soap+xml media type.

APPLICATION_FORM_URLENCODED

Represent application/x-www-form-urlencoded media type.

APPLICATION_PDF

Represent application/pdf media type.

IMAGE_JPEG

Represent image/jpeg media type.

IMAGE_GIF

Represent image/gif media type.

IMAGE_PNG

Represent image/png media type.

MULTIPART_FORM_DATA

Represent multipart/form-data media type.

MULTIPART_MIXED

Represent multipart/mixed media type.

MULTIPART_ALTERNATIVE

Represent multipart/alternative media type.

Represent multipart/related media type.

MULTIPART_PARALLEL

Represent multipart/parallel media type.

TEXT_PLAIN

Represent text/plain media type.

TEXT_HTML

Represent text/html media type.

TEXT_XML

Represent text/xml media type.

ENCODE_ERROR

Identifies encoding errors.

DECODE_ERROR

Identifies decoding errors.

GENERIC_MIME_ERROR

Identifies generic errors related to MIME.

SET_HEADER_FAILED

Identifies set header failures.

READING_HEADER_FAILED

Identifies header parsing errors.

PARSER_ERROR

Identifies entity body parsing errors.

INVALID_CONTENT_TYPE

Identifies errors related to content-type header.

HEADER_UNAVAILABLE

Identifies errors related to header unavailability.

IDLE_TIMEOUT_TRIGGERED

Identifies errors related to read/write timeouts.

BOUNDARY

Key name for boundary parameter in MediaType. This is needed for composite type media types.

START

Key name for start parameter in MediaType. This determines which part in the multipart message contains the payload.

TYPE

Key name for type parameter in MediaType. This indicates the MIME media type of the root body part.

CHARSET

Key name for charset parameter in MediaType. This indicates the character set of the body text.

DEFAULT_CHARSET

Default charset to be used with MIME encoding and decoding.

CONTENT_ID

Represents content-id header name.

CONTENT_LENGTH

Represents content-length header name.

CONTENT_TYPE

Represents content-type header name.

CONTENT_DISPOSITION

Represents content-disposition header name.

Types

Error

Represents MIME related errors.

Errors

DecodeError

Represents a DecodeError with a detailed message.

EncodeError

Represents an EncodeError with a detailed message.

GenericMimeError

Represents a GenericMimeError with a detailed message.

HeaderUnavailableError

Represents a HeaderUnavailableError with a detailed message.

IdleTimeoutTriggeredError

Represents a IdleTimeoutTriggeredError with a detailed message.

InvalidContentTypeError

Represents an InvalidContentTypeError with a detailed message.

ParserError

Represents a ParserError with a detailed message.

ReadingHeaderFailed

Represents a ReadingHeaderFailed error with a detailed message.

SetHeaderError

Represents a SetHeaderError with a detailed message.