0%

Js 转换 input File 到 Blob

问题

想从 input 输入框中拿到文件流,转换为 blob 的数据

解决

StackOverflow 上的

···html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

```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 示例

1
2
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

<!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>

参考文章