Javascript 将数据文件转换为 blob
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33855167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert data file to blob
提问by Fulrus
How to get a blob?
如何获得一团?
HTML:
HTML:
<input type="file" onchange="previewFile()">
JavaScript:
JavaScript:
function previewFile() {
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
// Get blob?
console.log(file);
}
回答by rafaelcastrocouto
As pointed in the comments, file
is a blob
:
正如评论中指出的,file
是一个blob
:
file instanceof Blob; // true
And you can get it's content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader
您可以使用文件阅读器 API https://developer.mozilla.org/en/docs/Web/API/FileReader获取它的内容
Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
阅读更多:https: //developer.mozilla.org/en-US/docs/Using_files_from_web_applications
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);
<input type="file">
<textarea rows="10" cols="50"></textarea>
回答by Dipo
A file object is an instance of Blob but a blob object is not an instance of File
文件对象是 Blob 的实例,但 Blob 对象不是 File 的实例
new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true
new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false
new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.
如果必须将文件对象转换为 Blob 对象,则可以使用文件的数组缓冲区创建新的 Blob 对象。请参阅下面的示例。
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
console.log(blob);
};
reader.readAsArrayBuffer(file);
回答by Zhenchuan Ren
async function FileToString (file) {
try {
let res = await file.raw.text();
console.log(res);
} catch (err) {
throw err;
}
}