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ŒHLËLŒHˆÝ[OH™[˜X›KX˜XÚÙÜ›Ý[™›™]ÈLËLŒHLËLŒNȈ[œÜXÙOHœ™\Ù\™H‚Ï‚‚OÏ‚‚BOÏ‚‚BBOÏ‚‚BBBOÏ‚‚BBBBO]Ý[OH™š[ˆÍȈH“LLLËŽLË‹Ž˜Í‹ŒÌLKÌ‹
ËŒÍKŒM‹‹ŒÍÎÌ΂BBBBBXËMKŒMKLŒN
LMKMËMKŽMLËL‹ŒÎ
‹MKŽÌ˜ËM‹ŒÌLËNÍMËŒÍKLŒML‹ŒÍÍËLÌ΂BBBBBPÎL‹ÎNÌ‹
ÍLËŒNN‹Ì
KLLËŽ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‹ŒÌË
Ž
LKŽ
svg support would be nice, any ideas?
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, "\\$&");
}