javascript 是否可以上传文本文件以在 HTML/JS 中输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19038919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:08:50  来源:igfitidea点击:

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

javascripthtml

提问by Sachin

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

我在 HTML 表单中有一些输入框,当表单加载时需要更新这些输入框,并且需要从文本文件上传这些值。
这里也问了一个类似的问题: 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?

我在互联网上搜索过这个,但找不到任何正确的答案。所以我想知道这是否可能?

回答by Jon Jaques

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.

如果您希望走客户端路线,您会对 HTML5 FileReader API 感兴趣。不幸的是,浏览器对此的支持并不广泛,因此您可能需要考虑谁将使用该功能。我认为适用于最新的 Chrome 和 Firefox。

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

这是一个实际示例:http: //www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

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

我也在这里阅读以找到readAsText方法:http: //www.w3.org/TR/file-upload/#dfn-readAsText

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

我会做这样的事情(为简洁起见,jQuery):http: //jsfiddle.net/AjaDT/2/

Javascript

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

回答by Fabian von Ellerts

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

另一个答案很好,但有点过时,它需要 HTML 和 jQuery 才能运行。

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

这是我的做法,适用于所有现代浏览器,直到 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()