I am passing base64 encoded data from a canvas element to an express handler that saves the data into a png file
What should I set contentType to in my ajax call below? (Using the default i.e not x-www-form-urlencoded gives me a png file that doesn't open)
$("#save").click(function(){
var canv = document.getElementById('imageView');
var canvData = canv.toDataURL('image/png');
console.log("the type is " + typeof canvData);
$.ajax({
type: "POST",
url: '/upload',
data: canvData,
contentType: '???',
success: function(data){
console.log(data);
}
});
});
For completeness my express handler is here:
// insert an image
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
var fs = require('fs');
app.post('/upload', function(req, res){
var image = req.body;
image = objToString(image);
var noHeader = image.substring(image.indexOf(',') + 1);
var decoded = new Buffer(noHeader, 'base64');
fs.writeFile('testfile.png', decoded, function(err){
res.send("without header " + noHeader + "decoded " + decoded);
});
});
The data URL you'll get is a base64 string like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY....
The specs mention the toBlob method in the canvas API to directly get the data as raw PNG. However, it's not implemented yet in the latest version of Chrome, so I wouldn't use it as-is.
If you want to get the raw PNG data (and thus use the image/png Content-Type), you can use this toBlob polyfill.
EDIT: After double-checking my code, I send the Data URL as JSON.
In the client:
$.ajax({
url: '/api/1/activities/' + self.model.id + '/attachments/' + fileName,
type: 'PUT',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({data: canv.toDataURL('image/png'}),
success: function () { ... }
});
In the server:
function parseDataURL(body) {
var match = /data:([^;]+);base64,(.*)/.exec(body);
if(!match)
return null;
return {
contentType: match[1],
data: new Buffer(match[2], 'base64')
};
}
app.post('/upload', function (req, res) {
var upload = parseDataURL(req.body.data);
...
});