FileReader .result is undefined
时间: 2023-10-20 22:07:19 浏览: 95
FileReader.js.zip
`FileReader.result` is undefined until the `load` event fires on the `FileReader` object. This is because the `FileReader` API reads files asynchronously and the `load` event is fired only after the file has been completely read.
Here's an example of how to use `FileReader` to read a file and display its contents:
```javascript
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.addEventListener('load', (event) => {
const fileContent = event.target.result;
console.log(fileContent);
// Do something with the file content
});
reader.readAsText(file);
});
```
In this example, we're listening for the `change` event on a file input element, creating a new `FileReader` object, and using the `readAsText` method to read the contents of the selected file. Once the file has been read, the `load` event is fired and we can access the file content using the `result` property on the `FileReader` object.
阅读全文