为什么node.js转换POST正文? [英] Why node.js convert POST body?

查看:118
本文介绍了为什么node.js转换POST正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想要将JPG二进制主体数据保存到OpenShift中的文件系统.但是以某种方式收到的信息将被转换.你知道为什么吗node.js是否有可能将数据视为文本并对其进行编码/解码?

Want to save JPG binary body data to file system in OpenShift. But somehow received info will get converted. Do you have any idea why? Is it possible that node.js treat data as text and does an encoding / decoding on it?

var myServer = http.createServer(function(request, response)
{
    var data = '';

    request.on('data', function (chunk){
        data += chunk;
    });

    request.on('end',function(){

    var date = new Date();
    var url_parts = url.parse(request.url,true);

    if(url_parts.pathname == '/setImage') {

        if(data != null && data.length > 0) {

            fs.writeFile('/var/lib/openshift/555dd1415973ca1660000085/app-root/data/asset/' + url_parts.query.filename, data, 'binary', function(err) {
                if (err) throw err
                console.log(date + ' File saved. ' + url_parts.query.filename  + ' ' + data.length)

                response.writeHead(200)
                response.end()
            })
        }
    }

推荐答案

您正在使用字符串初始化data,因此将chunk+=一起添加到它也会将大块也转换为字符串(其中接受字符编码.

You are initializing data with a string, so adding chunk's with += to it will convert the chunks to string as well (which is subject to character encoding).

相反,您应该将块收集为Buffer的数组,并使用 创建最终的缓冲区:

Instead, you should collect the chunks as an array of Buffer's and use Buffer.concat() to create the final Buffer:

var chunks = [];

request.on('data', function (chunk){
    chunks.push(chunk);
});

request.on('end', function() {
  var data = Buffer.concat(chunks);
  ...
});

这篇关于为什么node.js转换POST正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆