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.

MIME specific terms

The following terms are MIME specific and are extracted from the MIME specification.

Entity

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

Body Part

This refers to an entity that is inside a multipart entity.

Body

This is the body of an entity, which can be a body of a message or the body of a multipart entity.

Header Fields

Content-Type, Content-Transfer-Encoding, Content-ID, Content-Description, and Content-Disposition are some of the MIME header fields. These headers exist along with the other headers in the Entity.

Content-Type: image/jpeg
Content-Disposition: attachment; filename=genome.jpeg;
Content-Description: a complete map of the human genome

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/io;
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(untaint 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(untaint 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 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.toString();
            } 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

The sample given below 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

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

Decodes a given input with MIME specific Base64 encoding scheme.

base64DecodeBlob

Decodes a given byte[] with Base64 encoding scheme.

base64Encode

Encodes a given input with MIME specific Base64 encoding scheme.

base64EncodeBlob

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
prepareEncodingErrorWithDetail

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
DECODE_ERROR
GENERIC_MIME_ERROR
INIT_FAILED
SET_HEADER_FAILED
READING_HEADER_FAILED
PARSER_ERROR
INVALID_CONTENT_TYPE
HEADER_UNAVAILABLE
IDLE_TIMEOUT_TRIGGERED
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

MimeError

Errors

DecodeError
EncodeError
GenericMimeError
HeaderUnavailableError
IdleTimeoutTriggeredError
InitializingError
InvalidContentTypeError
ParserError
ReadingHeaderFailed
SetHeaderError