Node.js 使用内容处置作为文件名下载文件 [英] Node.js Download File Using Content Disposition as Filename
问题描述
我正在使用请求模块来下载文件,但是当文件名必须来自内容处理"标头时,我不太确定如何将响应通过管道传输到输出流.所以基本上,我需要读取响应直到找到标头,然后将其余部分通过管道传输到该文件名.
I'm using the Request module to download files, but I'm not quite sure how to pipe the response to an output stream when the filename must come from the 'Content-Disposition' header. So basically, I need to read the response until the header is found, and then pipe the rest to that filename.
示例显示如下:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'));
我想做的地方(伪代码):
Where I want to do (pseudocode):
var req = request('http://example.com/download_latest_version?token=XXX');
var filename = req.response.headers['Content-Disposition'];
req.pipe(fs.createWriteStream(filename));
我可以使用请求回调获取文件名:
I could get the filename using the Request callback:
request(url, function(err, res, body) {
// get res headers here
});
但这不会否定使用管道而不将下载的文件加载到内存中的好处吗?
But wouldn't that negate the benefits of using pipe and not loading the downloaded file into memory?
推荐答案
我正在从 yahoo 请求图像,但它没有使用 content-disposition
标头,但我正在提取 date
和 content-type
标题来构造文件名.这似乎与你想要做的很接近......
I'm reqesting a image from yahoo and it isn't using the content-disposition
header but I am extracting the date
and content-type
headers to construct a filename. This seems close enough to what you're trying to do...
var request = require('request'),
fs = require('fs');
var url2 = 'http://l4.yimg.com/nn/fp/rsz/112113/images/smush/aaroncarter_635x250_1385060042.jpg';
var r = request(url2);
r.on('response', function (res) {
res.pipe(fs.createWriteStream('./' + res.headers.date + '.' + res.headers['content-type'].split('/')[1]));
});
请忽略我的图片选择:)
Ignore my image choice please :)
这篇关于Node.js 使用内容处置作为文件名下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!