59
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

JS: base64文字列をBlob形式のFileに変換する

■概要

base64文字列で表現されたImageをUnit8Arrayコンストラクタ・Blobコンストラクタ・atobメソッドを利用して、Blob形式のfileに変換する方法。

■コード

code
//引数はbase64形式の文字列
function toBlob(base64) {
    var bin = atob(base64.replace(/^.*,/, ''));
    var buffer = new Uint8Array(bin.length);
    for (var i = 0; i < bin.length; i++) {
        buffer[i] = bin.charCodeAt(i);
    }
    // Blobを作成
    try{
        var blob = new Blob([buffer.buffer], {
            type: 'image/png'
        });
    }catch (e){
        return false;
    }
    return blob;
}

■参考

https://developer.mozilla.org/ja/docs/Web/API/window.atob
https://developer.mozilla.org/ja/docs/Web/JavaScript/Typed_arrays/Uint8Array
https://developer.mozilla.org/ja/docs/DOM/Blob

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
59
Help us understand the problem. What are the problem?