Uploading base64 encoded image to Node.js server does not work

I am using MEAN.io and I am trying to load a base64 encoded image.

Client side, AngularJS:

// Image we're going to send it out var base64Image = files[i]; var file = { image: base64Image, type: type, filetype: extension, characterId: character._id }; var newFile = new MediaSendBase64(file); newFile.$save(function(image) { if ( !image ) { console.log('ERROR IMAGE'); } else { console.log('SUCCESS.'); console.log(image); } }); 

Server side, NodeJS, controller:

 app.use(bodyParser.json({limit: '50mb'})); app.use(bodyParser.urlencoded({limit: '50mb', extended: true})); exports.uploadBase64 = function(req, res, next) { var uploadPath = path.normalize(process.cwd() + '/packages/characters/public/assets/uploads/'), data = new Buffer(''), imgURL = undefined, // public URL to show the pic type = undefined; // In case the '/uploads' directoy doesn't exist if( !fs.existsSync(uploadPath) ) { fs.mkdirSync(uploadPath, 0755); } // Decoding the base64 image var data = new Buffer(req.body.image, 'base64'); // Creating the name for the file --> characterId + type + timestamp + extension var filename = req.body.characterId + '-' + req.body.type + '-' + new Date().getTime().toString() + '.' + req.body.filetype; // Writing the image to filesystem fs.writeFile(uploadPath + filename, data, function (err) { if ( err ) { console.log(err); return res.status(500).json({ error: 'Cannot upload the image. Sorry.' }); } console.log('SAVED ON HD'); console.log('FINISHING'); // Sending success response res.json({ imgURL: imgURL, type: type }); }); }; 

The fact is that the file stored in / uploads does not work. I do not see the image. The base64 image is sent and the file is written to the hard drive, but cannot be opened.

What happened? Any suggestion?

Thanks!

0
source share
1 answer

Perhaps you are trying to save a file with metadata. therefore make base64 decoded data invalid.

Here is what I mean:

 data:image/png;base64,iVBORw0KG.... 

Data: image / png; base64 is just meta and is not encoded using base64, so:

You need to separate it from the bite, then decode, and then save to disk.

I use this convenient function:

 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; } 

source: NodeJS write base64 image file

So edit how I use it:

  var decodedImg = decodeBase64Image(imgB64Data); var imageBuffer = decodedImg.data; var type = decodedImg.type; var extension = mime.extension(type); var fileName = "image." + extension; try{ fs.writeFileSync(".tmp/uploads/" + fileName, imageBuffer, 'utf8'); } catch(err){ console.error(err) } 

Where mime is a great node-mime lib. npm install mime.

+1
source

Source: https://habr.com/ru/post/975677/


All Articles