ballerina/mime package
Package Overview
This package provides functions to transmit and receive messages that have multiple parts, such as an attachment. 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 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 package 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 gets the message from each part of the body, converts the messages to a string
, and sends a response.
import ballerina/http;
import ballerina/io;
import ballerina/log;
import ballerina/mime;
@http:ServiceConfig {basePath:"/test"}
service<http:Service> test bind {port:9090} {
@http:ResourceConfig {
methods:["POST"],
path:"/multipleparts"
}
// The resource that handles multipart requests.
multipartResource(endpoint client, http:Request request) {
http:Response response = new;
// Get the body parts from the request.
match request.getBodyParts() {
// 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.
error err => {
response.statusCode = 500;
response.setPayload(err.message);
}
// If the body parts were returned, iterate through each body part and handle the content.
mime:Entity[] bodyParts => {
string content = "";
foreach part in bodyParts {
content = content + " -- " + handleContent(part);
}
response.setPayload(content);
}
}
client -> respond(response) but { error e => log:printError("Error in responding", err = e) };
}
}
// The function that handles the content based on the body part type.
function handleContent(mime:Entity bodyPart) returns (string) {
// Get the base type of the specific body part.
string baseType = check mime:getMediaType(bodyPart.getContentType())!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();
match payload {
error err => return err.message;
xml xmlContent => return xmlContent.getTextValue();
}
} else if (mime:APPLICATION_JSON == baseType) {
// If the base type is ‘application/json’, get the JSON content from body part.
var payload = bodyPart.getJson();
match payload {
error err => return err.message;
json jsonContent => {
return jsonContent.toString();
}
}
}
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 response
The sample given below creates a multipart request. It includes application/json
and text/xml
type content.
// 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;
file:Path fileHandler = new("ballerina/mime/file.xml", mime:APPLICATION_XML);
bodyPart2.setFileAsEntityBody(fileHandler);
//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, mime:MULTIPART_MIXED);
Objects Summary
Object | Description | ||
---|---|---|---|
ContentDisposition | Represents values in |
||
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 Summary
Return Type | Function and Description | ||
---|---|---|---|
blob | error | base64DecodeBlob(blob valueToBeDecoded) Decodes a given blob with Base64 encoding scheme. |
||
ioByteChannel | error | base64DecodeByteChannel(ballerina.io:ByteChannel valueToBeDecoded) Decodes a given ByteChannel with Base64 encoding scheme. |
||
string | error | base64DecodeString(string valueToBeDecoded, string charset) Decodes a given string with Base64 encoding scheme. |
||
blob | error | base64EncodeBlob(blob valueToBeEncoded) Encodes a given blob with Base64 encoding scheme. |
||
ioByteChannel | error | base64EncodeByteChannel(ballerina.io:ByteChannel valueToBeEncoded) Encodes a given ByteChannel with Base64 encoding scheme. |
||
string | error | base64EncodeString(string valueToBeEncoded, string charset) Encodes a given string with Base64 encoding scheme. |
||
ContentDisposition | getContentDispositionObject(string contentDisposition) Given the Content-Disposition as a string, gets the ContentDisposition object with it. |
||
MediaType | error | getMediaType(string contentType) Given the Content-Type in string, gets the MediaType object populated with it. |
Global Variables
Name | Data Type | Description | |
---|---|---|---|
APPLICATION_FORM_URLENCODED | string | Represent 'application/x-www-form-urlencoded' media type. |
|
APPLICATION_JSON | string | Represent 'application/json' media type. |
|
APPLICATION_OCTET_STREAM | string | Represent 'application/octet-stream' media type. |
|
APPLICATION_PDF | string | Represent 'application/pdf' media type. |
|
APPLICATION_SVG_XML | string | Represent 'application/svg+xml' media type. |
|
APPLICATION_XHTML_XML | string | Represent 'application/xhtml+xml' media type. |
|
APPLICATION_XML | string | Represent 'application/xml' media type. |
|
BOUNDARY | string | Key name for |
|
CHARSET | string | Key name for |
|
CONTENT_DISPOSITION | string | Represents |
|
CONTENT_ID | string | Represents |
|
CONTENT_LENGTH | string | Represents |
|
CONTENT_TYPE | string | Represents |
|
DEFAULT_CHARSET | string | Default charset to be used with MIME encoding and decoding. |
|
IMAGE_GIF | string | Represent 'image/gif' media type. |
|
IMAGE_JPEG | string | Represent 'image/jpeg' media type. |
|
IMAGE_PNG | string | Represent 'image/png' media type. |
|
MULTIPART_ALTERNATIVE | string | Represent 'multipart/alternative' media type. |
|
MULTIPART_FORM_DATA | string | Represent 'multipart/form-data' media type. |
|
MULTIPART_MIXED | string | Represent 'multipart/mixed' media type. |
|
MULTIPART_PARALLEL | string | Represent 'multipart/parallel' media type. |
|
MULTIPART_RELATED | string | Represent 'multipart/related' media type. |
|
START | string | Key name for |
|
TEXT_HTML | string | Represent 'text/html' media type. |
|
TEXT_PLAIN | string | Represent 'text/plain' media type. |
|
TEXT_XML | string | Represent 'text/xml' media type. |
|
TYPE | string | Key name for |
public function base64DecodeBlob(blob valueToBeDecoded) returns (blob | error)
Decodes a given blob with Base64 encoding scheme.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
valueToBeDecoded | blob | Content that needs to be decoded |
Return Type | Description | ||
---|---|---|---|
blob | error | A decoded |
public function base64DecodeByteChannel(ballerina.io:ByteChannel valueToBeDecoded) returns (ioByteChannel | error)
Decodes a given ByteChannel with Base64 encoding scheme.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
valueToBeDecoded | ballerina.io:ByteChannel | Content that needs to be decoded |
Return Type | Description | ||
---|---|---|---|
ioByteChannel | error | A decoded |
public function base64DecodeString(string valueToBeDecoded, string charset) returns (string | error)
Decodes a given string with Base64 encoding scheme.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
valueToBeDecoded | string | Content that needs to be decoded |
|
charset | string | utf-8 | Charset to be used |
Return Type | Description | ||
---|---|---|---|
string | error | A decoded |
public function base64EncodeBlob(blob valueToBeEncoded) returns (blob | error)
Encodes a given blob with Base64 encoding scheme.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
valueToBeEncoded | blob | Content that needs to be encoded |
Return Type | Description | ||
---|---|---|---|
blob | error | An encoded blob. In case of errors, an |
public function base64EncodeByteChannel(ballerina.io:ByteChannel valueToBeEncoded) returns (ioByteChannel | error)
Encodes a given ByteChannel with Base64 encoding scheme.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
valueToBeEncoded | ballerina.io:ByteChannel | Content that needs to be encoded |
Return Type | Description | ||
---|---|---|---|
ioByteChannel | error | An encoded |
public function base64EncodeString(string valueToBeEncoded, string charset) returns (string | error)
Encodes a given string with Base64 encoding scheme.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
valueToBeEncoded | string | Content that needs to be encoded |
|
charset | string | utf-8 | Charset to be used |
Return Type | Description | ||
---|---|---|---|
string | error | An encoded |
public function getContentDispositionObject(string contentDisposition) returns (ContentDisposition)
Given the Content-Disposition as a string, gets the ContentDisposition object with it.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
contentDisposition | string | Content disposition string |
Return Type | Description | ||
---|---|---|---|
ContentDisposition | A |
public function getMediaType(string contentType) returns (MediaType | error)
Given the Content-Type in string, gets the MediaType object populated with it.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
contentType | string | Content-Type in string |
Return Type | Description | ||
---|---|---|---|
MediaType | error |
|
public type ContentDisposition object
Represents values in Content-Disposition
header.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
fileName | string | Default filename for storing the bodypart, if the receiving agent wishes to store it in an external file |
|
disposition | string | Indicates how the body part should be presented (inline, attachment or as form-data) |
|
name | string | Represents the field name in case of |
|
parameters | map |
A set of parameters, specified in attribute=value notation |
-
<ContentDisposition> toString() returns (string)
Converts the
ContentDisposition
type to a string suitable for use as the value of a corresponding MIME header.Return Type Description string The
string
represnetation of theContentDisposition
object
public type Entity object
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.
-
<Entity> setContentType(string mediaType)
Sets the content-type to entity.
Parameter Name Data Type Default Value Description mediaType string Content type that needs to be set to the entity
-
<Entity> getContentType() returns (string)
Gets the content type of entity.
Return Type Description string Content type as a
string
-
<Entity> setContentId(string contentId)
Sets the content ID of the entity.
Parameter Name Data Type Default Value Description contentId string Content ID that needs to be set to entity
-
<Entity> getContentId() returns (string)
Gets the content ID of entity.
Return Type Description string Content ID as a
string
-
<Entity> setContentLength(int contentLength)
Sets the content length of the entity.
Parameter Name Data Type Default Value Description contentLength int Content length that needs to be set to entity
-
<Entity> getContentLength() returns (int | error)
Gets the content length of entity.
Return Type Description int | error Content length as an
int
-
<Entity> setContentDisposition(mime:ContentDisposition contentDisposition)
Sets the content disposition of the entity.
Parameter Name Data Type Default Value Description contentDisposition mime:ContentDisposition Content disposition that needs to be set to entity
-
<Entity> getContentDisposition() returns (ContentDisposition)
Gets the content disposition of entity.
Return Type Description ContentDisposition A
ContentDisposition
object -
<Entity> setBody(string|xml|json|blob|ballerina.io:ByteChannel|mime:Entity[] entityBody)
Sets the entity body with the given content.
Parameter Name Data Type Default Value Description entityBody string|xml|json|blob|ballerina.io:ByteChannel|mime:Entity[] Entity body can be of type
string
,xml
,json
,blob
,io:ByteChannel
orEntity[]
-
<Entity> setFileAsEntityBody(string filePath, string contentType)
Sets the entity body with a given file. This method overrides any existing
content-type
headers with the default content typeapplication/octet-stream
. The default valueapplication/octet-stream
can be overridden by passing the content type as an optional parameter.Parameter Name Data Type Default Value Description filePath string Represents the path to the file
contentType string application/octet-stream Content type to be used with the payload. This is an optional parameter.
application/octet-stream
is used as the default value. -
<Entity> setJson(json jsonContent, string contentType)
Sets the entity body with the given
json
content. This method overrides any existingcontent-type
headers with the default content typeapplication/json
. The default valueapplication/json
can be overridden by passing the content type as an optional parameter.Parameter Name Data Type Default Value Description jsonContent json JSON content that needs to be set to entity
contentType string application/json Content type to be used with the payload. This is an optional parameter.
application/json
is used as the default value. -
<Entity> getJson() returns (json | error)
Extracts JSON body from the entity. If the entity body is not a JSON, an error is returned.
Return Type Description json | error json
data extracted from the the entity body. Anerror
record is returned in case of errors. -
<Entity> setXml(xml xmlContent, string contentType)
Sets the entity body with the given XML content. This method overrides any existing content-type headers with the default content-type
application/xml
. The default valueapplication/xml
can be overridden by passing the content-type as an optional parameter.Parameter Name Data Type Default Value Description xmlContent xml XML content that needs to be set to entity
contentType string application/xml Content type to be used with the payload. This is an optional parameter.
application/xml
is used as the default value. -
<Entity> getXml() returns (xml | error)
Extracts
xml
body from the entity. If the entity body is not an XML, an error is returned.Return Type Description xml | error xml
data extracted from the the entity body. Anerror
record is returned in case of errors. -
<Entity> setText(string textContent, string contentType)
Sets the entity body with the given text content. This method overrides any existing content-type headers with the default content-type
text/plain
. The default valuetext/plain
can be overridden by passing the content type as an optional parameter.Parameter Name Data Type Default Value Description textContent string Text content that needs to be set to entity
contentType string text/plain Content type to be used with the payload. This is an optional parameter.
text/plain
is used as the default value. -
<Entity> getText() returns (string | error)
Extracts text body from the entity. If the entity body is not text compatible an error is returned.
Return Type Description string | error string
data extracted from the the entity body orerror
in case of errors. -
<Entity> getBodyAsString() returns (string | error)
Given an entity, gets the entity body as a string. Content type is checked during entity body construction which makes this different from getText() method.
Return Type Description string | error Entity body as a
string
orerror
in case of errors occurred during construction of the string body. -
<Entity> setBlob(blob blobContent, string contentType)
Sets the entity body with the given blob content. This method overrides any existing
content-type
headers with the default content typeapplication/octet-stream
. The default valueapplication/octet-stream
can be overridden by passing the content type as an optional parameter.Parameter Name Data Type Default Value Description blobContent blob Blob content that needs to be set to entity
contentType string application/octet-stream Content type to be used with the payload. This is an optional parameter.
application/octet-stream
is used as the default value. -
<Entity> getBlob() returns (blob | error)
Given an entity, gets the entity body as a
blob
. If the entity size is considerably large consider using getByteChannel() method instead.Return Type Description blob | error blob
data extracted from the the entity body. Anerror
record is returned in case of errors. -
<Entity> setByteChannel(ballerina.io:ByteChannel byteChannel, string contentType)
Sets the entity body with the given byte channel content. This method overrides any existing content-type headers with the default content-type
application/octet-stream
. The default valueapplication/octet-stream
can be overridden by passing the content-type as an optional parameter.Parameter Name Data Type Default Value Description byteChannel ballerina.io:ByteChannel Byte channel that needs to be set to entity
contentType string application/octet-stream Content-type to be used with the payload. This is an optional parameter.
application/octet-stream
is used as the default value. -
<Entity> getByteChannel() returns (ioByteChannel | error)
Given an entity, gets the entity body as a byte channel.
Return Type Description ioByteChannel | error An
io:ByteChannel
. Anerror
record will be returned in case of errors -
<Entity> getBodyParts() returns (Entity[] | error)
Given an entity, gets its body parts. If the entity body is not a set of body parts an error will be returned.
Return Type Description Entity[] | error An array of body parts(
Entity[]
) extracted from the entity body. Anerror
record will be returned in case of errors. -
<Entity> getBodyPartsAsChannel() returns (ByteChannel)
Given an entity, gets the body parts as a byte channel.
Return Type Description ByteChannel Body parts as a byte channel
-
<Entity> setBodyParts(mime:Entity[] bodyParts, string contentType)
Sets body parts to entity. This method overrides any existing
content-type
headers with the default content typemultipart/form-data
. The default valuemultipart/form-data
can be overridden by passing the content type as an optional parameter.Parameter Name Data Type Default Value Description bodyParts mime:Entity[] Represents the body parts that needs to be set to the entity
contentType string multipart/form-data Content-type to be used with the payload. This is an optional parameter.
multipart/form-data
is used as the default value. -
<Entity> getHeader(string headerName) returns (string)
Gets the header value associated with the given header name.
Parameter Name Data Type Default Value Description headerName string Represents header name
Return Type Description string Header value associated with the given header name as a
string
. If multiple header values are present, then the first value is returned. -
<Entity> getHeaders(string headerName) returns (string[])
Gets all the header values associated with the given header name.
Parameter Name Data Type Default Value Description headerName string The header name
Return Type Description string[] All the header values associated with the given header name as a
string[]
-
<Entity> getHeaderNames() returns (string[])
Gets all header names.
Return Type Description string[] All header names as a
string[]
-
<Entity> addHeader(string headerName, string headerValue)
Adds the given header value against the given header.
Parameter Name Data Type Default Value Description headerName string The header name
headerValue string Represents the header value to be added
-
<Entity> setHeader(string headerName, string headerValue)
Sets the given header value against the existing header. If a header already exists, its value is replaced with the given header value.
Parameter Name Data Type Default Value Description headerName string The header name
headerValue string Represents the header value
-
<Entity> removeHeader(string headerName)
Removes the given header from the entity.
Parameter Name Data Type Default Value Description headerName string Represents the header name
-
<Entity> removeAllHeaders()
Removes all headers associated with the entity.
-
<Entity> hasHeader(string headerName) returns (boolean)
Checks whether the requested header key exists in the header map.
Parameter Name Data Type Default Value Description headerName string The header name
Return Type Description boolean True if the specified header key exists
public type MediaType object
Describes the nature of the data in the body of a MIME entity.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
primaryType | string | Declares the general type of data |
|
subType | string | A specific format of the primary type data |
|
suffix | string | Identify the semantics of a specific media type |
|
parameters | map |
A set of parameters, specified in an attribute=value notation |
-
<MediaType> getBaseType() returns (string)
Gets ���primaryType/subtype+suffix��� combination in string format.
Return Type Description string Base type as a
string
from MediaType struct -
<MediaType> toString() returns (string)
Converts the media type to a
string
, suitable to be used as the value of a corresponding HTTP header.Return Type Description string Content type with parameters as a
string