Search code examples
node.jssvgbase64fswritefile

Node save filereader base64 svg upload with fs


I try to save images uploaded from the client, my code works nicely with png's and jpg's but not with svg's. What is the best way?

Client side: <input type="file> => fileReader.readAsDataURL => fileReader.result => xhr

Server side:

saveUserImage(userid, file, base64, callback) {
  if(file.type.indexOf('image') != 0)
    return callback(false);

  var fs = require("fs");

  var regEx = new RegExp('^data:' + file.type + ';base64,');
  base64 = base64.replace(regEx, "");

  fs.mkdir('imgs', function() {
    fs.writeFile('imgs/' + userid + "_" + file.name, base64, 'base64', function(err) {
      if(err) return callback(false);
      return callback('imgs/' + userid + "_" + encodeURIComponent(file.name));
    });
  });
}

The saved svg's are wrong encoded I think:

u«ZŠf {û/ƒìf•¶¬{®Þ[™\œÚ[ÛHŒKŒˆ[˜ÛÙ[™ÏHš\ÛËN
NKLHÏ‚KKHÙ[™\˜]ÜŽˆYØ™H[\ݘ]܈NKŒŒÕ‘È^ÜYËR[ˆˆÕ‘È™\œÚ[ÛŽˆ
‹ŒZ[
HKO‚ݙș\œÚ[ÛHŒKŒHˆYH“^Y\—ÌHˆ[œÏHš‹ËÝÝÝËÌ˛ܙËÌŒÜݙȈ[œÎž[šÏHš‹ËÝÝÝËÌ˛ܙËÌNNNKÞ[šÈˆHŒˆOHŒ‚‚HšY]ЛÞHŒLËLŒHLËLŒHˆÝ[OH™[˜X›KX˜XÚÙÜ›Ý[™›™]ÈLËLŒHLËLŒNȈ[œÜXÙOHœ™\Ù\™H‚Ï‚‚OÏ‚‚BOÏ‚‚BBOÏ‚‚BBBOÏ‚‚BBBBO]Ý[OH™š[ˆÍȈH“LLLËŽLË‹Ž˜Í‹ŒÌLKÌ‹
ËŒÍKŒM‹‹ŒÍÎÌ΂BBBBBXËMKŒMKLŒN
LMKMËMKŽMLËL‹ŒÎ
‹MKŽ̘ËM‹ŒÌLËNÍMËŒÍKLŒML‹ŒÍÍËLÌ΂BBBBBPÎL‹ÎNÌ‹
ÍLËŒNN‹Ì
KLLËŽLË‹Žžˆ‹Ï‚‚BBBOÙÏ‚‚BBBOÏ‚‚BBBBO]Ý[OH™š[ˆÌÌÌÍŒÐNȈH“NKŽLNK
ÌËŒÌ͘ËM‹ŒÌLËNÍMËŒÍKLŒML‹ŒÍÍËLÌ΂BBBBBXÍKŒM‹LLŒN
MKM‹LMKŽMLË‹ŒÎ
KLMKŽ̈‹Ï‚‚BBBOÙÏ‚‚BBBOÏ‚‚BBBBO]Ý[OH™š[ˆÌÌÌÍŒÐNȈH“NLŒŒK
ÍŽÍØËLŒL‹LŒŒÎLŒKLŒÍNLŒ˜ËL
ÍLŒ
‹LŽLMËLŒŒÍLKŒNM‹LŒM‚BBBBBXËM‹ŽLKNKLËMËŽ
KLŒKŽ
LKL‹MËLÌ‹ŒXÍKŒÌLËLLŒŽL‹MKÍÎKLM‹
‹ËŒÍÍ‹LM‹
˜ÌŒL‹ŒŒÎŒKŒÍNŒ‚‚BBBBBXÌ
ÍŒ
‹ŽLMËŒŒÍKŒNM‹ŒMØÍ‹ŽLKKLË
ËŽ
‹ŒKŽ
LK‹NÌ‹ŒPÌLL‹ŒÌË
Ž
LKŽ

svg support would be nice, any ideas?


Solution

  • The problem is, that the mime type of svg is image/svg+xml! The plus is not escaped and the regex does not match. I used a simple function to escape and now it works perfekt

    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }