前几天有个小伙伴找我,他在项目中想让一个视频文件点击下载时不是弹出新页面,而是提示下载,问我咋整。其实,解决办法很简单,就是在后端设置Content-Type为application/octet-stream,因为也不是一个小伙伴问过我这问题了,所以写个DEMO给大家参考参考
素材:https://raw.githubusercontent.com/nickdesaulniers/netfix/gh-pages/demo/frag_bunny.mp4
以nodejs代码为例,我将实现访问"/video"时跳转到浏览器的自带播放页面,
当访问"/frag_bunny.mp4"时弹出下载提示
代码:
var http = require('http');
var fs = require('fs');
var url = require('url');
var routes = {//<====路由
"/video"(request, response) {
fs.readFile("frag_bunny.mp4", 'binary', function (err, data) {
if (err) {
console.log(err);
response.writeHead(500, { 'Content-Type': 'text/html' });
} else {
response.writeHead(200, { 'Content-Type': 'video/mp4' });//<====mp4标识
response.write(data, 'binary');
}
response.end();
});
},
"/frag_bunny.mp4"(request, response) {
fs.readFile("frag_bunny.mp4", 'binary', function (err, data) {
if (err) {
console.log(err);
response.writeHead(500, { 'Content-Type': 'text/html' });
} else {
response.writeHead(200, { 'Content-Type': 'application/octet-stream' });//<====文件流标识
response.write(data, 'binary');
}
response.end();
});
},
"/"(request, response) {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(`
<a target= "_blank" href="/video">打开页面显示播放界面</a>
<br />
<a target= "_blank" href="/frag_bunny.mp4">打开页面提示下载</a>
`);
response.end();
},
"/404"(request, response) {
response.writeHead(404, { 'Content-Type': 'text/html' });
response.write("404");
response.end();
}
}
// 创建服务器
http.createServer(function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname;
// 输出请求的文件名
console.log("Request for " + pathname + " received.");
route = routes[pathname]
if (route) {
route(request, response);
} else {
routes["/404"](request, response);
}
}).listen(8889);
网友评论