在原生 JS我們可以這樣寫
</head>
<body>
<input type='file' onchange='onChooseFile(event)' />
</body>
<script type="text/javascript">
function onChooseFile(event) {
if (typeof window.FileReader !== 'function')
throw ("The file API isn't supported on this browser.");
let input = event.target;
if (!input)
throw ("The browser does not properly implement the event object");
if (!input.files)
throw ("This browser does not support the `files` property of the file input.");
if (!input.files[0])
return undefined;
let file = input.files[0];
let fr = new FileReader();
fr.onload = funResult;
fr.readAsText(file);
}
function funResult(event){
console.log( event.target.result)
}
</script>
<html>
React
//選擇檔案部份
//使用.bind(this) 使用箭頭函數( () => {}) 使最後一個作用域 ( this) 保持原樣
<input type="file" name="myFile" onChange={this.FileUploadHandler.bind(this)} />
//讀取文檔後文字存放的input
<input type="text" id="" name="" value={this.state.fileText} onChange={(event)=>this.setState({fileText:event.target.value})}/>
FileUploadHandler(event) {
if (typeof window.FileReader !== 'function')
throw ("The file API isn't supported on this browser.");
let input = event.target;
if (!input)
throw ("The browser does not properly implement the event object");
if (!input.files)
throw ("This browser does not support the `files` property of the file input.");
if (!input.files[0])
return undefined;
let file = input.files[0]
let fr = new FileReader()
fr.onload = (e)=> {
//this.setState({ fileText : e.target.result });
console.log(e.target.result)
this.setState({fileText:e.target.result})
}
fr.readAsText(file)
}