Is it possible to upload a text file to input in HTML/JS?

前端 未结 2 2009
栀梦
栀梦 2021-02-04 19:06

I have some input boxes in a HTML form that need to be updated when the form loads and these values need to be uploaded from a text file.
A similar question was also asked h

2条回答
  •  心在旅途
    2021-02-04 19:12

    If you wish to go the client side route, you'll be interested in the HTML5 FileReader API. Unfortunately, there is not wide browser support for this, so you may want to consider who will be using the functionality. Works in latest Chrome and Firefox, I think.

    Here's a practical example: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

    And I also read here to find the readAsText method: http://www.w3.org/TR/file-upload/#dfn-readAsText

    I would do something like this (jQuery for brevity): http://jsfiddle.net/AjaDT/2/

    Javascript

    var fileInput = $('#files');
    var uploadButton = $('#upload');
    
    uploadButton.on('click', function() {
        if (!window.FileReader) {
            alert('Your browser is not supported');
            return false;
        }
        var input = fileInput.get(0);
    
        // Create a reader object
        var reader = new FileReader();
        if (input.files.length) {
            var textFile = input.files[0];
            // Read the file
            reader.readAsText(textFile);
            // When it's loaded, process it
            $(reader).on('load', processFile);
        } else {
            alert('Please upload a file before continuing')
        } 
    });
    
    function processFile(e) {
        var file = e.target.result,
            results;
        if (file && file.length) {
            results = file.split("\n");
            $('#name').val(results[0]);
            $('#age').val(results[1]);
        }
    }
    

    Text file

    Jon
    25
    

提交回复
热议问题