locked
How do you pass results of HTML 5 input type of file to a javascript function? RRS feed

  • Question

  • Hi,

    In the Lightswitch HTML client I am using an HTML 5  input type="file" to prompt a user to choose a tab delimited text file. Once the name has been chosen I am calling a function to access a webAPI in javascript to take that file name picked as the  file to be imported. Here is sample code:

    /// <reference path="~/GeneratedArtifacts/viewModel.js" />
    var fileinput;
    myapp.ImportRecords.ImportFileName_render = function (element, contentItem) {
        // Write code here.
        fileinput = $('<input name="file" type="file" id="file" accept=".txt" onchange="handletheimport()"   style="margin-bottom: 10px;"  />');
        $(element).append(fileinput);
    
    
    };
    
    
    //function msg()
    //{ alert("HelloWorld");}
    
    function handletheimport() {
        msls.showProgress(msls.promiseOperation(function (operation) {
            $.post("../api/ImportRecords/ImportTheReportsToRecords",
                {
                    ReqParam: fileinput,
                    ReqParam2: "test"
    
                }
                )
            setTimeout(function () {
                operation.complete("Import Complete!");
            }, 5000);
        }).then(function (result) {
            msls.showMessageBox(result);
            screen.ReportsToRecords.refresh()
    
    
        }));
    }

    The onchange does call the function ( I confirmed that by testing with a dummy alert). BUT it doesnt seem to understand the 'fileinput' variable. I am not clear whether the fileinput declared is a string at this point or not. I am desiring to pass a string over to  WebAPI which represents the name of the txt file chosen.

    Can anyone tell me what I am doing wrong here? At the risk of exposing my ignorance ...  ;-)

    thanks

    Tuesday, May 27, 2014 3:28 AM

Answers

All replies

  • I depends on what data your webAPI is expecting.  Typically the file would be handled client side by the fileReader() object and then streamed binary to the server like this code is doing:

    http://code.msdn.microsoft.com/windowsdesktop/LightSwitch-HTML-Client-d243f5cb/sourcecode?fileId=77039&pathId=1367562979

    HTH,

    Josh

    • Marked as answer by lvsund Tuesday, May 27, 2014 8:06 PM
    Tuesday, May 27, 2014 1:10 PM
  • Thanks. I think that helps clarify what I need to consider/look at. So far, my thinking had been to just get the name of the text file on the client side and then pass that over to the server. But it sounds like from both the example and what you were saying above that the file reading and streaming needs to start on the client side.

    Will see if I can come up with an equivalent to the code above for streaming text file vis a vis uploading pic.

    Will mark as answer for now- and raise another question later if necessary- after coding in the above direction

    Thanks

    Tuesday, May 27, 2014 8:06 PM
  • Josh- thanks

    Your answer pointed me in the right direction with respect to a file reader object being used on the client side and streamed binary passed over to server. I did a slight variation on the code that was in the link you provided:

    myapp.ImportRecords2.ImportFileName_render = function (element, contentItem, previewStyle) {
        // Write code here.
        //FileImporter(element,contentItem);
        var relativePathFromClientRootToThisFolder = "Scripts/";
        //     (This path will be used for the fallback ASPX uploader.)
    
    
        var $element = $(element);
    
    
        // Try the local file-reading HTML-5 standard method first.
        //      If it fails, fall back on a method that will require an extra round-trip 
        //      to the server
        if (window.FileReader) {
            createHTML5Importer();
        } else {
            createFallbackASPXImporter();
        }
    
        function createHTML5Importer() {
            var $file_browse_button = $('<input name="file" type="file" accept=".txt" style="margin-bottom: 10px;" />');
            $element.append($file_browse_button);
    
            var $preview = $('<div></div>');
            $element.append($preview);
    
            $file_browse_button.bind('change', function handleFileSelect(evt) {
                var files = evt.target.files;
                if (files.length == 1) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        SetContentItem(e.target.result,  contentItem);
                    };
                    reader.readAsText(files[0]);
                } else {
                    // if no file was chosen (e.g., if file-choosing was cancelled),
                    //     explicity ensure that the content is set back to null:
                    SetContentItem(null,  contentItem);
                }
            });
        }
    
    function SetContentItem(textString,  contentItem) {
          
    
            if ((textString == null) || (textString.length == 0)) {
                contentItem.value = null;
            } else {
               
                contentItem.value = textString;
                //alert(contentItem.value);
                msls.showProgress(msls.promiseOperation(function (operation) {
                    $.post("../api/ImportRecords/ImportTheReportsToRecords",
                        {
                            ReqParam: contentItem.value,
                            ReqParam2: "test"
    
                        }
                        )
                    setTimeout(function () {
                        operation.complete("Import Complete!");
                    }, 5000);
                }).then(function (result) {
                    msls.showMessageBox(result);
                    screen.ReportsToRecords.refresh()
    
    
                }));
            }
        }
    

    I used the  reader to stream in as readastext.

    The stream is a parameter sent to the webAPI.

    The webAPI in turn uses StringReader in conjunction with TextFieldParser to recognize it as a tab delimited file:

                        Dim csvTextParser As New TextFieldParser(New StringReader(parameters.ReqParam))
    

    From there the normal parsing of fields and insertion in SQL table occurs.

    Thanks again for your advice - it pointed me in right direction!

    Thursday, May 29, 2014 4:33 AM