问题
想从 input 输入框中拿到文件流,转换为 blob 的数据
解决
StackOverflow 上的
···html
```js
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');
function readFile(event) {
textarea.textContent = event.target.result;
console.log(event.target.result);
}
function changeFile() {
var file = input.files[0];
var reader = new FileReader();
reader.addEventListener('load', readFile);
reader.readAsText(file);
}
input.addEventListener('change', changeFile);
MDN 示例
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
function previewFile() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
// convert image file to base64 string
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
还有个方法是 createObjectURL
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>URL.createObjectURL example</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<input type="file">
<img>
<p class="p">The URL of this image is : </p>
</body>
<script>
var Element = document.querySelector('input');
var img = document.querySelector('img');
Element.addEventListener('change', function() {
var url = URL.createObjectURL(Element.files[0]);
img.src = url;
console.log(url);
var d=document.querySelector(".p");
d.textContent+=url;
});
</script>
</html>