7

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 here: Uploading Text File to Input in Html/JS

I have searched for this on the internet, but couldn't find any correct answer. So I want to know whether it is possible or not?

9
  • yes, it's possible. use input type=file Commented Sep 26, 2013 at 21:21
  • 2
    Do you mean you have a text file you want to read and append into your html or you want to handle a form upload with js? Commented Sep 26, 2013 at 21:23
  • What values, what input boxes, what needs to be updated, what format is the file, where is the file, uploaded to where ... WTF maybe it would be more clear if you posted some code Commented Sep 26, 2013 at 21:47
  • for example there is a input box, it needs to be filled automatically at the start time when it is loaded, and i must be able to change it afterwards Commented Sep 26, 2013 at 22:03
  • Basically, you need to process an uploaded file and update the page/form accordingly based on the contents of the file, right? Commented Sep 26, 2013 at 22:06

2 Answers 2

15

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
Sign up to request clarification or add additional context in comments.

6 Comments

tried the above jsfiddle, in that i am able to browse the files, and select some text file, but when i submit upload button, nothing is happening, what is the reason for this? is it because of the browser issue? did the above code work fine for you ?
Yeah, works for me in Chrome and Firefox. Did the file you uploaded contain the text I suggested? Updated my answer to show that. However, parsing text is not really in the scope of this question. Once you have the text in a variable (in this case file inside of processFile), you can do whatever you want with it.
yeah this works now.. i am sorry i also want to know how this works with php or when the file is on the server side ? i.e. when i have access with backend, in this case also i need to select a text file, match the text file values with the javascript ids and then enter the input values..
FileReader is also supported by IE 10. About support: caniuse.com/#search=filereader
@JonJaques in the above, if the text file contents are, Name: Jon Age: 25, but i want to extract only 'Jon' in the first line and '25' in the second line and input them in the html boxes as it was done previously, is it possible to do that ?
|
3

The other answer is great, but a bit outdated and it requires HTML & jQuery to run.

Here is how I do it, works in all modern browsers down to IE11.

/**
 * Creates a file upload dialog and returns text in promise
 * @returns {Promise<any>}
 */
function uploadText() {
    return new Promise((resolve) => {
        // create file input
        const uploader = document.createElement('input')
        uploader.type = 'file'
        uploader.style.display = 'none'

        // listen for files
        uploader.addEventListener('change', () => {
            const files = uploader.files

            if (files.length) {
                const reader = new FileReader()
                reader.addEventListener('load', () => {
                    uploader.parentNode.removeChild(uploader)
                    resolve(reader.result)
                })
                reader.readAsText(files[0])
            }
        })

        // trigger input
        document.body.appendChild(uploader)
        uploader.click()
    })
}

// usage example
uploadText().then(text => {
     console.log(text)
})
// async usage example
const text = await uploadText()

1 Comment

Thanks–this is great! One side note: in some contexts, the call to uploader.click() won’t work, because some browsers require human intervention to initiate a file upload. (The current version of Chrome/Mac, for example, generates an error in the console log when it encounters that uploader.click() line.) In that case, you can leave out the uploader.style.display = 'none' line, and manually click the button to test it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.