Read a File Using the FTP Connector

In Mule 4, the FTP connector can read a file at any point in the flow, unlike in Mule 3 where transport could only read files as a result of inbound endpoint polling.

When the file is read from the FTP source folder, the default behavior of the operation in Mule 4 is that it remains in the same folder until it is manually deleted.

Here is the syntax for reading a file:

<ftp:read path="#[path]"
  outputMimeType="application/xml" />

The operation above reads the file in the given path. It returns a Mule message (MuleMessage) 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 a FTP:ILLEGAL_PATH error. Note that the operation does not read directories.

MIME Types and Encoding

Each connector tries to determine a file’s MIME type (mimeType) 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 outputMimeType parameter.

The same process works for encoding. By default, the connector assumes that the default encoding in the Mule runtime matches the MIME type of the file. However, you can set the encoding through the outputEncoding parameter.

Why MIME Types Matter

DataWeave expressions are embeddable inside operations that generate payloads and other values. Having the correct mimeType 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 only protects the file from other flows in the same Mule application. These locks do not protect the file from external processes. However, if the Mule app is running on a cluster, the lock is distributed.

The file lock is automatically released when one of the following occurs:

  • The Mule flow that locked the file ends.

  • The file content has been fully read.

Note: If the file is already locked by someone else, the connector cannot unlock it, and you then receive a FTP:FILE_LOCK error.

The Read operation makes use of the repeatable streams functionality introduced in Mule 4. The operation returns a list of messages, where each message represents a file in the list and holds a stream to the file. A stream is repeatable by default.

For more information on this topic, see Streaming in Mule 4.