来自Busboy

时间:2015-07-10 18:21:43

标签: node.js stream multipartform-data restify busboy

我遇到了Busboy的奇怪问题。我正在使用Invoke-RestMethod从PowerShell上传文件到Node.js编写的远程服务器。如果我使用流函数,代码没有任何问题。它接受二进制数据并将文件写入本地驱动器而不会打嗝。但是,当我使用Busboy时,它给了我“缺少边界错误”。为了解决这个问题,我将边界传递给Invoke-RestMethod。这会导致边界错误,但Busboy根本不会启动文件事件。我一直在摸不着头脑,试图弄清楚已经两天了,解决方案似乎无法解决。几周前,相同的代码工作得很好,但现在已经不复存在了。我不确定是否对工作环境做出了任何改变,但非常奇怪。

流代码:这很好用

服务器代码

fs = require('fs');
server = restify.createServer();
server.post('/file',restify.queryParser(),uploadFile);    
function uploadFile(req, res, next) {   
    var wstream = fs.createWriteStream("x.jpg");
    req.pipe(wstream);
}

Powershell的

$upload= Invoke-RestMethod -Uri "http://localhost:8088/file" -Method Post -InFile $imagePath -ContentType 'multipart/form-data'

Busboy代码:这会引发Missing Boundary错误

服务器代码

fs = require('fs');
server = restify.createServer();
server.post('/file',restify.queryParser(),uploadFile);    
function uploadFile(req, res, next) {   
    var fileStream = new BusBoy({ headers: req.headers });  
}

Powershell的

$upload= Invoke-RestMethod -Uri "http://localhost:8088/file" -Method Post -InFile $imagePath -ContentType 'multipart/form-data'

带有边界集和修改后的Node.js代码的Powershell代码。 “存档”不会被调用。

Powershell的

$begin = @"
---BlockBoundary---
"@

$end = @"
---BlockBoundary---
"@

Add-Content 'RequestBodySavedToFile' $begin
$imageData = Get-Content $imagePath -Raw -Encoding Byte
Add-Content 'RequestBodySavedToFile' $imageData -Encoding Byte
Add-Content 'RequestBodySavedToFile' $end

$url = "http://localhost:8088/file"
$contentType = "multipart/form-data; boundary=$begin"
$upload= Invoke-RestMethod -Uri $url1 -Method Post -InFile "RequestBodySavedToFile" -ContentType $contentType

服务器代码

fs = require('fs');
server = restify.createServer();
server.post('/file',restify.queryParser(),uploadFile);    
function uploadFile(req, res, next) {   
    var fileStream = new BusBoy({ headers: req.headers });                      

    req.pipe(fileStream);       

    fileStream.on('file', function(fieldname, file, filename, encoding, mimetype) {
        console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); 
        res.end();      
    });
}

知道造成这种情况的原因是什么?我非常感谢所有的投入。

1 个答案:

答案 0 :(得分:1)

没有file事件的原因是因为请求数据没有根据multipart/form-data正确格式化(您至少缺少每个部分的相应标头)。

相关问题