简体   繁体   English

设置“ Content-disposition”而不设置“ Content-Length”是否可以接受?

[英]Is it acceptable to set 'Content-disposition' without 'Content-Length'?

I have a simple Express.js route: 我有一个简单的Express.js路由:

app.get('/db/csv', function (req, res) {
    db.users.find({}, { _id: 0 }, function (err, docs) {
        var csv = /* compute from docs */;

        res.setHeader('Content-disposition', 'attachment; filename=users.csv');
        res.send(csv);
    });
});

I use this route to download a CSV version of my "users" database. 我使用此路由下载“用户”数据库的CSV版本。 Setting the Content-disposition HTTP response header will trigger the "Save as…" dialog in the browser. 设置Content-disposition HTTP响应标头将在浏览器中触发“另存为...”对话框。

Should I also set a Content-Length header? 是否还应该设置Content-Length标头? I've seen it in an example and I'm not sure if it's required here. 我已经在一个示例中看到了它,但不确定在这里是否需要它。 If it's required, how would I calculate the size value from the csv variable (which is a JavaScript string)? 如果需要,我如何从csv变量(这是一个JavaScript字符串)计算大小值?

(Btw, the functionality in the browser works without Content-Length .) (顺便说一句,浏览器中的功能无需Content-Length 。)

It's not required, it's perfectly fine to set just Content-Disposition . 这不是必需的,只设置Content-Disposition是完全可以的。 For instance, there's nothing in RFC2616 or RFC6266 requiring you combine them. 例如, RFC2616RFC6266中没有任何内容要求您将它们组合在一起。

If it's required, how would I calculate the size value from the csv variable (which is a JavaScript string)? 如果需要,我如何从csv变量(这是一个JavaScript字符串)计算大小值?

It isn't, but that doesn't mean it's not nice to include. 不是,但这并不意味着包含它不是很好。 :-) I haven't done this with NodeJS, but I'd say convert it to a buffer with the appropriate encoding (eg, the encoding you're including in charset ) and get the size of the buffer in bytes. :-)我还没有使用NodeJS做到这一点,但我想说的是将其转换为具有适当编码的缓冲区(例如,您在charset包含的编码),并以字节为单位获取缓冲区的大小。 Since you're then going to send that buffer as the content, and the buffer's told you how big it is, that should be accurate. 因为您将要发送该缓冲区作为内容,并且缓冲区告诉您缓冲区有多大,所以应该准确。

Content-Length and Content-Disposition are orthogonal. Content-Length和Content-Disposition是正交的。

If you don't send Content-Length, you'll have to use Transfer-Encoding chunked. 如果不发送Content-Length,则必须使用分块的Transfer-Encoding。 (Usually, your HTTP library will do this for you) (通常,您的HTTP库将为您完成此操作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM