Node.js 铬不';不显示下载进度节点api
为什么它不显示我通过nodejs提供服务的文件的下载进度?这是否与我如何将管道分块传输到HTTP响应有关?该文件必须通过流媒体提供,因为它非常大。我试图修改标题以包含内容长度,但随后我的服务器出现502错误Node.js 铬不';不显示下载进度节点api,node.js,Node.js,为什么它不显示我通过nodejs提供服务的文件的下载进度?这是否与我如何将管道分块传输到HTTP响应有关?该文件必须通过流媒体提供,因为它非常大。我试图修改标题以包含内容长度,但随后我的服务器出现502错误 app.get("/download", function(res, res){ const fs = require("fs"); var file = fs.createReadStream("bigfile.txt"); res.set({"Content-Di
app.get("/download", function(res, res){
const fs = require("fs");
var file = fs.createReadStream("bigfile.txt");
res.set({"Content-Disposition" : "attachment; filename=bigfile.txt", "Content-Type" : "application/octet-stream"});
file.pipe(res);
});
res.download()
解决您的问题。它在内部使用res.sendFile()
传输文件sendFile
执行一些额外的操作,例如根据文件名和内容长度设置正确的HTTP内容类型头。设置“内容类型”时:“应用程序/八位字节流”
额外头“传输编码:分块”
将由express添加
分块数据以一系列分块的形式发送。内容长度标题
在本例中,在每个块的开头都省略了
以十六进制格式添加当前块的长度,后跟
“\r\n”,然后是块本身,后跟另一个“\r\n”。这个
终止区块是常规区块,但其
长度为零。然后是拖车,拖车由
(可能为空)实体标题字段的序列。
在这里阅读有关传输编码的更多信息
使用res.download()时的响应头
手动设置“内容处置”:“附件;文件名=bigfile.txt”
和“内容类型”:“应用程序/八位字节流”
您也可以自己测试,下面是基本代码:
app.js
const express = require('express');
const app = express();
const http = require('http');
const fs = require('fs');
app.get("/",function(req,res){
res.sendFile(__dirname+'/index.html');
})
app.get('/download', function(req, res){
const file = `${__dirname}/sample.txt`;
res.download(file); // Set disposition and send it.
// const file = fs.createReadStream(`${__dirname}/sample.txt`);
// res.set({"Content-Disposition" : "attachment; filename=bigfile.txt",
//"Content-Type" : "application/octet-stream"});
// file.pipe(res);
});
http.createServer(app).listen(80);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h3>Hello HTTP!</h3>
<a href="http://localhost/download">download</a>
</body>
</html>
你好
你好,HTTP!
在Chrome浏览器中运行并检查两种情况下的响应标题
重要信息如果您对大文件使用反向代理,如nginx
,您可能需要配置:
是的,关于502的更多详细信息吗?我正在代理它,在我的代理上我得到502(代理服务器收到来自上游服务器的无效响应)。当我直接尝试时,它会下载但不显示大小。您是否尝试过res.download
helper?至少还有一些额外的错误处理需要完成。
const express = require('express');
const app = express();
const http = require('http');
const fs = require('fs');
app.get("/",function(req,res){
res.sendFile(__dirname+'/index.html');
})
app.get('/download', function(req, res){
const file = `${__dirname}/sample.txt`;
res.download(file); // Set disposition and send it.
// const file = fs.createReadStream(`${__dirname}/sample.txt`);
// res.set({"Content-Disposition" : "attachment; filename=bigfile.txt",
//"Content-Type" : "application/octet-stream"});
// file.pipe(res);
});
http.createServer(app).listen(80);
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h3>Hello HTTP!</h3>
<a href="http://localhost/download">download</a>
</body>
</html>