1

我对 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);
}

电源外壳

$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 });  
}

电源外壳

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

具有边界集和修改过的 Node.js 代码的 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();      
    });
}

知道是什么原因造成的吗?我非常感谢所有输入。

4

1 回答 1

1

没有file事件的原因是因为请求数据的格式不正确multipart/form-data(您至少缺少每个部分的适当标题)。

于 2015-07-14T05:39:46.307 回答