mobileFX WebKitX ActiveX
Advanced Topics / Working with Blob and Uint8Array
In This Topic
    Working with Blob and Uint8Array
    In This Topic

    WebKitX supports read and write of Blob and Uint8Array byte arrays from files directly in JavaScript by exposing the following methods on the main window frame:

    • window.WriteUint8ArrayToFile(filename, array)
    • window.ReadUint8ArrayFromFile(filename)
    • window.WriteBlobToFile(filename, blob)
    • window.ReadBlobFromFile(filename)

    The methods accept both absolute and relative paths. To use relative paths like the example below, you must handle the OnCreate event and set Settings.application_cache to an existing folder path.

    You must make sure that the FileSystem permissions allow read and write on the files and their parent folders or the methods will fail. Please note those methods should be used with reason regarding the size of the data that are read or written to the files and they are provided for saving small files like Excel workbooks, documents, reports, etc.

     The following code demonstrates exporting an Excel XLSX file using Excel JS JavaScript Library:

     

     

    Excel JS Sample Code
    Copy Code
    <html>
        <head>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.1.1/exceljs.js"></script>
            <head>
            <body></body>
            <script>
            window.onload = function()
            {
                // Create workbook & add worksheet
                        
                const workbook = new ExcelJS.Workbook();
                const worksheet = workbook.addWorksheet('ExampleSheet');
    
                // Add column headers
                        
                worksheet.columns = [{ header: 'Package', key: 'package_name' },
                                        { header: 'Author', key: 'author_name' }];
    
                // Add row using key mapping to columns
               
                worksheet.addRow({ package_name: "ABC", author_name: "Author 1" },
                                    { package_name: "XYZ", author_name: "Author 2" });
    
                // Add rows as Array values
    
                worksheet.addRow(["BCD", "Author Name 3"]);
    
                // Add rows using both the above of rows
    
                const rows = [["FGH", "Author Name 4"], { package_name: "PQR", author_name: "Author 5" }];
                worksheet.addRows(rows);
               
                // Save workbook to file
               
                workbook.xlsx.writeBuffer().then(data =>
                {
                    const blob = new Blob([data], { type: 'application/octet-stream' });
                    WriteBlobToFile("test1.xlsx", blob);
                });
               
                // Alternative - using WriteUint8ArrayToFile
                               
                workbook.xlsx.writeBuffer().then(data =>
                {
                    const blob = new Blob([data], { type: 'application/octet-stream' });
                    blob.arrayBuffer().then(arrayBuffer => 
                                            WriteUint8ArrayToFile("test2.xlsx", new Uint8Array(arrayBuffer)));          
                }); 
               
                // Loading
                               
                var bytes = ReadUint8ArrayFromFile("test.xlsx");
               
                var blob = ReadBlobFromFile("test.xlsx");
                               
            }
            </script>
    </html>

      

    CEF3 implements local storage API but you cannot read and write your data to a physical file on your disk, but rather to a virtual file system in your application's cache. Again you must handle the OnCreate event and set Settings.application_cache to an existing folder path. The methods above by-pass the use of storage APIs allowing you to read and write files directly on your hard disk but your might need to edit your JavaScript libraries to get them to work. The code above demonstrates how to use the methods with Excel JS, a famous JavaScript library for creating and manipulating Excel workbooks.

    Regarding the storage API, the webkitRequestFileSystem method lets you ask for PERSISTENT or TEMPORARY storage. Persistent storage is storage that stays in the browser unless the app or the user removes it, but the user must grant you permission before you can use it. In contrast, temporary storage is automatically granted without any user permission, but it can be expunged by the browser at any time. To use PERSISTENT storage with the File System API, CEF3 exposes a requestQuota API. So to request storage, you need to do something like the following:

     

    webkitRequestFileSystem
    Copy Code
    <!DOCTYPE html>
    <html>
        <head>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
            <meta charset=utf-8 />
            <title>Chrome File API tester</title>
    
            <script>
                window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
    
                // Handle errors
                function errorHandler(e) {
                    var msg = '';
    
                    switch (e.code) {
                        case FileError.QUOTA_EXCEEDED_ERR:
                            msg = 'QUOTA_EXCEEDED_ERR';
                            break;
                        case FileError.NOT_FOUND_ERR:
                            msg = 'NOT_FOUND_ERR';
                            break;
                        case FileError.SECURITY_ERR:
                            msg = 'SECURITY_ERR';
                            break;
                        case FileError.INVALID_MODIFICATION_ERR:
                            msg = 'INVALID_MODIFICATION_ERR';
                            break;
                        case FileError.INVALID_STATE_ERR:
                            msg = 'INVALID_STATE_ERR';
                            break;
                        default:
                            msg = 'Unknown Error';
                            break;
                    };
                    console.log('Error: ' + msg);
                }
            
                // Init and write some data to a file
                function onInitFs(fs) {
                    fs.root.getFile('log-f-api.txt', {create: true}, function(fileEntry) {
    
                        fileEntry.isFile === true;
                        fileEntry.name == 'log-f-api.txt';
                        fileEntry.fullPath == '/log-f-api.txt';
                        // Create a FileWriter object for our FileEntry (log.txt).
                        fileEntry.createWriter(function(fileWriter) {
    
                            fileWriter.onwriteend = function(e) {
                                console.log('Write completed.');
                            };
    
                            fileWriter.onerror = function(e) {
                                console.log('Write failed: ' + e);
                            };
    
                            // Create a new Blob and write it to log.txt.
                            if (!window.BlobBuilder && window.WebKitBlobBuilder)
                                window.BlobBuilder = window.WebKitBlobBuilder; // in Chrome 12.
                            var bb = new BlobBuilder(); 
                            bb.append("some stuff");
                            console.log("bb size:"+bb.size);
                            bb.append('put some nice text in our file....');
                            var ourData = bb.getBlob('text/plain');
                            fileWriter.write(ourData); 
                        }, errorHandler);
                    }, errorHandler);
                }
    
                // start the party
                $(function() {
                    document.getElementById('hello').innerHTML = 'start the tests';
                    window.requestFileSystem(window.PERSISTENT, 5*1024*1024, onInitFs,errorHandler);
                });
            
            </script>
    
        </head>
        <body>
            <p id="hello">Tester FIle API</p>
    
            <h4>Other links</h4>
            <ul>
                <li>http://code.google.com/chrome/extensions/trunk/fileBrowserHandler.html#event-onExecute</li>
                <li>http://html5rocks.com</li>
            </ul>
    
        </body>
    </html>