https://www.cnblogs.com/bruce-gou/p/6399766.html
没有使用express框架,主要是对于 request 的监听,data的时候对数据进行保存,end的时候对所有的数据进行处理
前端使用FileReader,将图片转成base64,后端代码实现过程:
var http = require(‘http‘); var fs = require(‘fs‘); var path = require(‘path‘) http.createServer(function (req, res) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type"); res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.setHeader("X-Powered-By", ‘ 3.2.1‘) res.setHeader("Content-Type", "application/json;charset=utf-8"); if (req.method == "OPTIONS") { res.statusCode = 200; return res.end(‘ok‘); } /*让options请求快速返回*/ var val = [] req.on(‘data‘, function (chunk) { val.push(chunk); }) req.on(‘end‘, function () { var bufferVal = Buffer.concat(val); bufferVal = bufferVal.toString(‘utf8‘); var imgData = JSON.parse(bufferVal).imageFile; var base64 = imgData.base64Code.replace(/^data:image\/\w+;base64,/, ""); //去掉图片base64码前面部分data:image/png;base64 var dataBuffer = new Buffer(base64, ‘base64‘); fs.writeFile(path.join(__dirname, imgData.filename), dataBuffer, (err) => { if (err) throw err; console.log(‘The file has been saved!‘); }); }) res.end(‘Hello World‘) }).listen(3000, function () { console.log(‘server is running...‘) })
原文地址:https://www.cnblogs.com/wuqiuxue/p/9189763.html
时间: 2024-10-28 12:49:24