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:
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/pngContent-Type), you can use this toBlob polyfill.EDIT: After double-checking my code, I send the Data URL as JSON.
In the client:
In the server: