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

前端 未结 2 2048
栀梦
栀梦 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:23

    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}
     */
    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()
    

提交回复
热议问题