zoukankan      html  css  js  c++  java
  • Node.js——post方式提交的图片如何保存

    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...')
    })
  • 相关阅读:
    校验参考相关备份
    API接口设计
    redis 基础配置
    Apollo 统一配置中心
    http返回状态码记录
    ngnix实战
    OAuth2三方授权
    OAuth2授权协议记录
    KMP算法
    分治法
  • 原文地址:https://www.cnblogs.com/wuqiuxue/p/9189763.html
Copyright © 2011-2022 走看看