Search code examples
node-red

is there a way to send a file to a custom node form in Node-Red?


In a custom node, I want to provide the possibility to auto-populate form data using a file. So I need to allow a file upload in edit form.

In my custom node, I would like to allow to send a file to a custom end point (made via RED.admin.post) that parse the file and output a json to the caller.

Is there a way to do this?


Solution

  • I solved in this way:

    In template .html file

    
    <script type="text/x-red" data-template-name="...">
    
        <input id="myFile" type="file" name="fileToParse">
        <input id="file-submit" type="submit" value="Import data from file" name="submit">
    ...
    
             oneditprepare: function () {
                $('#file-submit').click(function (e) {
                    var fd = new FormData();
                    fd.append('file', $('#myFile')[0].files[0]);
                    var file = fd.get('file');
                    var blb = file.slice();
                    var reader = new FileReader();
                    // This fires after the blob has been read/loaded.
                    reader.addEventListener('loadend', (e) => {
                        var fileData = e.srcElement.result;
                        console.log(fileData);
                        $.ajax({
                            url: '/mynode/file-parse',
                            data: {fileData: fileData},
                            method: 'POST',
                            success: function (data) {
                                populateForm(data);
                            }
                        });
                    });
                    // Start reading the blob as text.
                    reader.readAsBinaryString(blb);
                });
    

    And in .js:

    
     RED.httpAdmin.post("/mynode/file-parse", function (req, res) {
            var output = [];
            var fileData = req.body.fileData;
            // ... parse fileData end produce output
            res.json(output)
        });