LoginSignup
76
64

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-08-28

■概要

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

76
64
6

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
76
64