LoginSignup
5
3

More than 3 years have passed since last update.

ZIP圧縮されたファイルのbase64文字列からファイルを表示する。

Last updated at Posted at 2019-06-27

※ほぼ自分用メモ。
e-Gov法令APIでは,法令に書式等が含まれている場合,その書式の画像やPDFを一つのZIPに纏めたものをBase64文字列にしたものを,ImageData要素のテキストとして返します。
そこで,このBASE64文字列から元のファイルを復元し,たとえばHTML内に表示したりすることが考えられます。
ImageData要素からのテキストの取り出しはまぁ後でやるとして,とりあえずファイルをちゃんと取り出すところまで。
法技研六法に組み込んだら,もうちょっと丁寧に書き直すかも。

  1. Base64文字列をバイナリに変換
  2. バイナリ文字列をUint8Arrayに変換
  3. Zlib.Unzipを使って,2.のUint8Arrayを解凍
  4. 解凍したものに含まれる各ファイル(Uint8Arrayになっている)をBase64文字列に変換
  5. Base64文字列ファイルを,HTMLに埋め込む。

1. Base64文字列をバイナリに変換

var imageData = "UEsDBBQACAgIAJx4204AAA(中略)AAAA";
var binaryString = atob(imageData);

2 バイナリ文字列をUint8Arrayに変換

var u8a = Uint8Array.from(binaryString.split(""), e => e.charCodeAt(0))

3. Zlib.Unzipを使って解凍

var unzipped = new Zlib.Unzip(u8a);

4. 各ファイルをBase64文字列に変換

var b64s = [];
var filenames = unzipped.getFilenames();
for(var i in filenames ){
    var buffer = unzipped.decompress( filenames[i] );
    var arr = Array.from(buffer, e => String.fromCharCode(e)String.fromCharCode(e)).join(""));
    b64s[i] = arr.join("");
}

5. HTMLに埋め込む(PDFの場合)

for(var i in b64s){
  var obj = document.createElement("object");
  obj.setAttribute("type", "application/pdf" );
  obj.setAttribute("data", "data:application/pdf;base64,"+b64s[i]);
  obj.setAttribute("width", "100%");
  obj.setAttribute("height", "100%");

  document.body.appendChild(obj);
}

参考文献:
-http://var.blog.jp/archives/62330155.html
-https://github.com/imaya/zlib.js
-https://qiita.com/katzueno/items/c490361c3274d0108e7d
-https://stackoverflow.com/questions/43234936/providing-the-object-tag-with-data-directly
-https://www.e-gov.go.jp/elaws/pdf/houreiapi_shiyosyo.pdf

5
3
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
5
3