Read a File Using the SFTP Connector Example - Mule 4
Anypoint Connector for SFTP (SFTP Connector) can read a file at any point in the flow. The Read operation reads the file in the given path and returns a Mule message with the following attributes:
-
The file’s content as the payload
-
The file’s metadata in the message attributes
-
If the file does not exist, you receive an
SFTP:ILLEGAL_PATH
errorNote that the operation does not read directories.
Configure the Read Operation in Studio
To add and configure the Read operation in Studio, follow these steps:
-
In the Mule Palette view, search for
sftp
and select the Read operation. -
Drag the Read operation onto the Studio canvas.
-
In the General tab of the operation configuration screen, click the plus sign (+) next to the Connector configuration field to access the global element configuration fields.
-
Specify the connection information and click OK.
-
In the General tab, set the File Path field to the path of the file to read, for example,
#[path]
. -
In the Advanced tab, set the MIME Type field to
application/xml
and the Encoding field toISO 10646/Unicode(UTF-8)
.
The following screenshot shows the Read operation configuration:
In the XML editor, the <sftp:read>
configuration looks like this:
<sftp:read path="#[path]"
lock="true|false"
outputEncoding="UTF-8"
outputMimeType="application/xml" />
MIME Types and Encoding
Each connector determines a file’s MIME type from its extension. However, if first-hand knowledge of the file’s content is necessary, you can force the MIME type to a different value with the MIME Type (outputMimeType
) parameter.
The same process works for encoding. By default, the connector assumes that the default encoding in the Mule runtime engine matches the MIME type of the file. However, you can set the encoding through the Encoding (outputEncoding
) parameter.
Why MIME Types Matter
DataWeave expressions are embeddable inside operations that generate payloads and other values. Having the correct MIME Type set helps DataWeave auto-assign types and also generate the correct outputs. Also, maximizing the use of DataSense’s functionality improves the user experience.
File Locks
File system level locks are not possible in FTP or SFTP, so each operation uses a Mule lock that protects only the file from other flows in the same Mule application. These locks do not protect the file from external processes. However, if the Mule application is running on a cluster, the lock is distributed.
The file lock is automatically released when any of the following occurs:
-
The Mule flow that locked the file ends
-
The file content has been fully read
If the file is already locked by someone else, the connector cannot unlock it, resulting in a SFTP:FILE_LOCK error.
|