Closed FukMo10 closed 8 years ago
npm test
//サーバサイドで取得したバイナリファイルを画像として保存 var NCMB = require("./ncmb_js/lib/ncmb"); var fs = require('fs'); var ncmb = new NCMB("api_key", "client_key"); ncmb .set("protocol", "https:") .set("fqdn", "mb.api.cloud.nifty.com") .set("port", 443); var downloadName = "your_file_name.png"; var saveName = "dl.png"; ncmb.File.download(downloadName) .then(function(data){ fs.writeFileSync(saveName, data, 'binary'); console.log(data); }) .catch(function(err){ console.log(err); });
<!-- フロントエンドで取得したバイナリファイルを画像として表示 --> <html> <header> <script src="./ncmb_js/ncmb.min.js"></script> <script> var ncmb = new NCMB("api_key", "client_key"); var fileName = "your_file_name.png"; </script> </header> <body> <canvas id="sample"></canvas> <script> ncmb.File.download(fileName, "arraybuffer") .then(function(res){ //encode arraybuffer to String var bytes = new Uint8Array(res); var binaryData = ""; for (var i = 0, len = bytes.byteLength; i < len; i++) { binaryData += String.fromCharCode(bytes[i]); } //estimate mime type var imgSrc = "data:image/unknown;base64,"; if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[bytes.byteLength-2] === 0xff && bytes[bytes.byteLength-1] === 0xd9) { imgSrc = "data:image/jpeg;base64,"; } else if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) { imgSrc = "data:image/png;base64,"; } else if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) { imgSrc = "data:image/gif;base64,"; } else if (bytes[0] === 0x42 && bytes[1] === 0x4d) { imgSrc = "data:image/bmp;base64,"; } var image = new Image(); //encode to base64 image.src = imgSrc + window.btoa(binaryData); image.onload = function() { try { var canvas = document.getElementById('sample'); if (canvas.getContext) { var context = canvas.getContext('2d'); context.drawImage(image, 0, 0, image.width, image.height); } } catch (exp) { // エラー処理 return; } }; }) .catch(function(err){ console.log(err); }); </script> </body> </html>
概要
確認事項
npm test
が成功すること確認用サンプルコード