node系列之 base64 转文件

在node环境中,利用Buffer和fs能把base64转成文件形式存储

              
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
var fs = require('fs'); var data = 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA..kJggg=='; function decodeBase64Image(dataString) { var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), response = {}; if (matches.length !== 3) { return new Error('Invalid input string'); } response.type = matches[1]; response.data = new Buffer(matches[2], 'base64'); return response; } var imageBuffer = decodeBase64Image(data); console.log(imageBuffer); // { type: 'image/jpeg', // data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 b4 00 00 00 2b 08 06 00 00 00 d1 fd a2 a4 00 00 00 04 67 41 4d 41 00 00 af c8 37 05 8a e9 00 00 ...> } fs.writeFile('test.jpg', imageBuffer.data, function(err) { ... });

有用就赞一下吧 😃

本文于 2018/3/21 下午 发布在 编程 分类下,当前已被围观 3213 次

相关标签:node

永久地址:https://blog.pandashuai.com/article/4