Example: Write Binary Files
The mapping illustrated below reads BLOB values from a SQLite database and writes image files to the disk. The database has a table called products, which has the following columns (fields):
•id (integer, the unique permanent serial number of the record)
•title (text, the title of the product)
•description (text, the product's description)
•picture (blob, the product's image)
For the scope of this example, only the id and picture fields are relevant.
The goal of the mapping is to extract all pictures from the products table and write them as files to the disk. As illustrated above, the write-binary-file function is used for that purpose. The first argument, filepath, receives the file path for each image. The path must be unique to avoid overriding any files, so it is generated by concatenating the unique database id of each record with the word "image" and then adding the ".png" file extension (it is assumed that all pictures are in PNG format). Note that the path is relative, so the files will be written to the same directory as the mapping.
The second argument, content, receives the binary content stored in the database.
The count function returns a count of all generated files, and combines this number with the string "file(s) written". This provides a report as to how many files were actually generated by the mapping. In this example, the database contains only two product records, so the mapping output reflects this:
As stated previously, this function generates temporary files when the mapping runs in preview execution. To preview each individual file, use the arrow buttons to navigate to the record of interest, click the Open with button, and select an image editor.
To save all files, click the Save generated output or Save all generated outputs toolbar button, as applicable.