返回列表

base64编码上传问题

默认分类 2015/11/12 10:09

https://cnodejs.org/topic/51f49b07f4963ade0e59be2d

'use strict';

var http = require('http');

var Buffer = require('buffer').Buffer;

var boundaryKey = Math.random().toString(16); //随机数,目的是防止上传文件中出现分隔符导致服务器无法正确识别文件起始位置
console.log(boundaryKey);

var options = {
    host: '127.0.0.1',
    port: 3000,
    path: '/file',
    method: 'POST'
};

var request = http.request(options, function (req) {
    console.log('statusCode: ', req.statusCode);
    console.log('headers: ', req.headers);

    req.on('data', function (body1) {
        console.log('body:' + body1);
    });
});

var png = 'iVBORw0KGgoAAAANSUhEUgAAAAQAAAAEAQMAAACTPww9AAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAADUExURRhJ6DolURQAAAALSURBVAjXY2CAAAAACAABLyDdMQAAAABJRU5ErkJggg==';

var payload = [
    '--' + boundaryKey + '\r

', 'Content-Type: image/png\r ', 'Content-Disposition: form-data; name="a"; filename="5.png"\r ', 'Content-Transfer-Encoding: base64\r \r ', png ].join('');

console.log(payload.length);

var enddata = '\r

--' + boundaryKey + '--'; console.log('enddata:' + enddata.length);

request.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundaryKey + '');
request.setHeader('Content-Length', Buffer.byteLength(payload) + Buffer.byteLength(enddata));

request.on('error', function (e) {
    console.error('error:' + e);
});

request.write(payload);

request.end(enddata);