LoginSignup
1
0

More than 1 year has passed since last update.

Javascript Blob個人まとめ

Last updated at Posted at 2022-08-13

JacascriptのBlobとは

Blobは0や1で表すバイナリーデータをもとにファイル(Blob)を作成することができる。
そのおかげで、PDFや画像を保存してダウンロードできるようにする。

  • いろいろな形式のファイルを扱うことができる

不変の生データであるファイルのようなオブジェクト

テキストやバイナリーデータとして読み込んだり、ReadableStream に変換してそのメソッドを使ったデータ処理ができる

blob 例(テキストをダウンロード)
// 形式を指定してBlobを作成。第一引数に[data],第二引数に形式
const blob = new Blob(['hello world'],{type:"text/plain"});

// ダウンロード用のリンクを作成
const link = document.createElement('a');
// BlobをもとにURLを作成
const url = URL.createObjectURL(blob);
link.href = url
// ダウンロード実行
link.click()
link.download = 'hoge.txt';
link.parentNode?.removeChild;

URLの作成はFileReader クラスでも作成可能だが、URL.createObjectURLの方がシンプルではやいよう

blob の URL を作成する方法は両方とも使用可能です。しかし、通常は URL.createObjectURL(blob) がよりシンプルで速いです。
https://ja.javascript.info/blob

let link = document.createElement('a');
link.download = 'hello.txt';
let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
let reader = new FileReader();
reader.readAsDataURL(blob); // blob を base64 へ変換し onload を呼び出します
reader.onload = function() {
 link.href = reader.result; // data url
 link.click();
};

Stream

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0