我正在尝试创建multer中间件,以便通过superagent将流式文件从客户端传输到第三方。
const superagent = require('superagent');
const multer = require('multer');
// my middleware
function streamstorage(){
function StreamStorage(){}
StreamStorage.prototype._handleFile = function(req, file, cb){
console.log(file.stream) // <-- is readable stream
const post = superagent.post('www.some-other-host.com');
file.stream.pipe(file.stream);
// need to call cb(null, {some: data}); but how
// do i get/handle the response from this post request?
}
return new StreamStorage()
}
const streamMiddleware = {
storage: streamstorage()
}
app.post('/someupload', streamMiddleware.single('rawimage'), function(req, res){
res.send('some token based on the superagent response')
});
我认为这似乎有效,但我不确定如何处理来自超级POST
请求的响应,因为我需要返回从超级请求中收到的令牌。
我已尝试post.end(fn...)
,但显然是end
和pipe
can't both be used together。我觉得我误解了管道是如何工作的,或者我试图做的事情是否切合实际。
答案 0 :(得分:3)
Superagent的.pipe()
方法用于下载(将数据从远程主机传输到本地应用程序)。
您似乎需要在另一个方向上进行管道传输:从您的应用程序上传到远程服务器。在superagent(从v2.1开始),没有方法,它需要一个不同的方法。
您有两种选择:
最简单,效率最低的是:
告诉multer缓冲/保存文件,然后使用.attach()
上传整个文件。
更难的是“手动”“管道”文件:
data
个事件,并使用每个数据块调用superagent的.write()
方法。end
事件,并调用superagent的.end()
方法来读取服务器的响应。