Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 472
Sachin Avatar asked Sep 26 '13 21:09

Sachin


People also ask

How to upload a file using HTML?

The same is true for uploading files, we only need three steps: In HTML, we can use the input element. Just set the type of this element to file, then the element can be used to select the file. After the user selects a file, the metadata of the file will be stored in the files property of this input element.

What is the use of input file in HTML?

The $input file is used to choose single or multiple files from the storage on any device. This means that once any file has been chosen or specified, the browser can upload it to the server using various types of form submissions. To create a functional HTML input file syntax, you must use the HTML type attribute and include the file value.

How to create a text input field in HTML?

To sum up, to create a text input field in HTML, you need at least: An <input> element, which typically goes inside a <form> element. To set the type attribute to have a value of text. This will create a single line text input field. Don't forget to add a name attribute.

What is an HTML type file?

In other words, web developers use the HTML type file for handling various types of data submitted by users. The required syntax for the file input in HTML documents is easy to create and only requires a couple of attributes.


2 Answers

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
like image 104
Jon Jaques Avatar answered Nov 14 '22 22:11

Jon Jaques


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()
like image 30
Fabian von Ellerts Avatar answered Nov 14 '22 22:11

Fabian von Ellerts