gpt4 book ai didi

node.js - Busboy 的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:13 26 4
gpt4 key购买 nike

我在使用 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 代码:这会引发“缺失边界”错误

服务器代码

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 代码。不会调用“On file”。

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

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

最佳答案

没有 file 事件的原因是请求数据未根据 multipart/form-data 正确格式化(您至少缺少适当的 header 对于每个部分)。

关于node.js - Busboy 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com