Upload File as String to JavaScript Variable

前端 未结 2 1717
长发绾君心
长发绾君心 2020-12-28 18:29

Is there any way for a client to upload a file in an HTML form (e.g. .txt or .csv formats) to a JavaScript variable as a string using only JavaScript? If so, could you prov

2条回答
  •  不知归路
    2020-12-28 18:45

    Here is a quick and dirty example based on a form named "myform" that contains a file input named "myfile" :

    document.forms['myform'].elements['myfile'].onchange = function(evt) {
        if(!window.FileReader) return; // Browser is not compatible
    
        var reader = new FileReader();
    
        reader.onload = function(evt) {
            if(evt.target.readyState != 2) return;
            if(evt.target.error) {
                alert('Error while reading file');
                return;
            }
    
            filecontent = evt.target.result;
    
            document.forms['myform'].elements['text'].value = evt.target.result;
        };
    
        reader.readAsText(evt.target.files[0]);
    };
    

    Here's the associated HTML form:

    and a jsfiddle to demo it.

提交回复
热议问题