Last active
December 3, 2017 20:53
-
-
Save msurguy/e6f9665f6490ee3e4cfe7d4ec9347452 to your computer and use it in GitHub Desktop.
save D3 as SVG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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