angularjs - 使用 Node Buffer 或 fileStream 进行 formData 文件上传

标签 angularjs node.js fs

更新:我已经使用 multipart (app.use(multipart({uploadDir: __dirname + '/../uploads'})) 或多或少解决了问题来自 these instructions ),但仍然不知道为什么我的原始代码(如下)失败。

这个问题有很多变体,我尝试过其中的想法但没有成功。我正在使用 file uploading directive (并且此后尝试了另一种开源替代方案)将二进制文件发送到 Node 服务器,该服务器运行以下代码(基于我现在无法重新找到的SO答案):

exports.receive = function(req, res) {

    var fitFileBuffer = new Buffer('');
    // req.setEncoding("binary");    //doesn't help

    req.on('data', function(chunk) { 
        fitFileBuffer = Buffer.concat([fitFileBuffer, chunk]);
    });

    req.on('end', function() { 
        fs.writeFileSync(
            "today2.fit",
            fitFileBuffer,
            'binary');
        res.send(200);
    });
};

如果我上传 today.fit 并与 today2.fit 进行比较,它们具有相同的 Kb 数据,但不相同,后续代码无法处理文件。鉴于这种情况发生在两段第三方代码上,我怀疑问题出在我的代码上。

以下是客户端发出的 POST 的详细信息 Network settings

最佳答案

最后,当我意识到我想避免保存到磁盘时,我使用 busyboy 网站上的一些内容和我自己使用的缓冲区修改了 Generalhenry 的代码:

exports.receive = function (req, res, next) {
    var busboy = new Busboy({ headers: req.headers });
    var fileBuffer = new Buffer('');

    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        file.on('data', function(data) {
            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
            fileBuffer = Buffer.concat([fileBuffer, data]);
        });

        file.on('end', function() {
            console.log('File [' + fieldname + '] Finished');
            genXmlFromString(fileBuffer.toString(), function(data) {
                res.json(data);
            });
        });

    });

    busboy.on('finish', function() {
        console.log("'finish'");
    });

    req.pipe(busboy);
};

关于angularjs - 使用 Node Buffer 或 fileStream 进行 formData 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27680258/

相关文章:

node.js - ansible 有支持 npm start 的模块吗?

file - Node.js:如何在不上传文件列表的情况下检查文件夹是否为空

angularjs - 判断表单输入是否有焦点

javascript - 在生产模式下运行时,yeoman 应用程序中不显示图像

node.js - 当我执行 res.json (newschema) 时,Postman 上不再显示属性

node.js 是并发运行的吗?

node.js - fs.writeFileSync 类型错误 : lazyErrmapGet is not a function or its return value is not iterable

javascript - 带有选项 'a' 的 Node.js fs.open 生成 EACCES 错误

javascript - 在本地主机上运行我的程序时,它找不到 .js 文件,也找不到我的 Bootstrap 的来源

css - 在鼠标悬停时可见的 div 中 Bootstrap datetimepicker