【Javascript】Data URLとBlobの相互変換、ダウンロード
Data URLをBlobに変換
URLをfetchで取得する。
let dataUrl = "data:image/png;base64,~~~base64エンコードしたバイナリ~~~"
fetch(dataUrl)
.then(response => response.blob())
.then(blob => {
console.log(blob)
})
BlobをData URLに変換
FileReaderを使う。
let blob = new Blob(['画像のバイナリなど'],{type: 'image/png'})
let reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = function(){
dataUrl = reader.result
console.log(dataUrl)
}
Blobをダウンロードさせる
URL.createObjectURL()を使ってURLを作って、a要素に入れて、click()。
function download(blob, fileName) {
if (window.navigator.msSaveOrOpenBlob) {
// for IE,Edge
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
// for chrome, firefox
const url = URL.createObjectURL(new Blob([blob], {type: 'text/csv'}));
const a = document.createElement('a');
a.href = url;
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(url);
a.parentNode.removeChild(a);
}
}
Data URLをダウンロードさせる
a要素のhref属性にそのまま入れてclick()。
let type = 'image/png'
let filename = 'test.png'
let data = 'base64エンコードしたファイルの内容'
const a = document.createElement('a');
a.href = 'data:' + type + ';base64,' + data;
a.setAttribute('download', filename);
document.body.appendChild(a);
a.click();