Skip to content

Instantly share code, notes, and snippets.

@msurguy
Last active December 3, 2017 20:53
Show Gist options
  • Select an option

  • Save msurguy/e6f9665f6490ee3e4cfe7d4ec9347452 to your computer and use it in GitHub Desktop.

Select an option

Save msurguy/e6f9665f6490ee3e4cfe7d4ec9347452 to your computer and use it in GitHub Desktop.
save D3 as SVG
const oReq = new XMLHttpRequest();
oReq.open("POST", 'http://localhost:3000/upload', true);
oReq.onload = function (oEvent) {
console.log('uploaded!');
// File was Uploaded ok.
};
// var html = d3.select("svg").node().parentNode.innerHTML;
const svgDoctype = '<?xml version="1.0" standalone="no"?>'
+ '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
// serialize our SVG XML to a string.
let svgString = (new XMLSerializer()).serializeToString(d3.select('svg').node());
// RegEx to round the path coordinates (1.146994119497445 to 1.1, or if using toFixed(2), to 1.15) in order to trim the file size by a lot
svgString = svgString.replace(/([\-+]?\d{1,}\.\d{3,}([eE][\-+]?\d+)?)/g, function(x){ return (+x).toFixed(1) });
const blob = new Blob([ svgDoctype + svgString], { type: 'image/svg+xml;charset=utf-8' });
oReq.send(blob);
const bodyParser = require('body-parser');
app.use(bodyParser.raw({ type: 'image/svg+xml', limit: '50mb' }))
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.post('/upload', function(req, res) {
var fs = require('fs');
//console.log(req.body);
fs.writeFile('public/uploads/' + Date.now() + ".svg", req.body, 'binary', function (err){
if(err) {
return console.log(err);
}
console.log("The file was saved!");
res.send('File uploaded!');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment