前幾天有個小夥伴找我,他在項目中想讓一個視訊檔案點選下載下傳時不是彈出新頁面,而是提示下載下傳,問我咋整。其實,解決辦法很簡單,就是在後端設定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);