Node.js——post方式提交的圖片如何保存

https://www.cnblogs.com/bruce-gou/p/6399766.htmlhtml

沒有使用express框架,主要是對於 request 的監聽,data的時候對數據進行保存,end的時候對全部的數據進行處理前端

前端使用FileReader,將圖片轉成base64,後端代碼實現過程:express

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...')
})
相關文章
相關標籤/搜索