[英]How to make these links to download files when clicked in node.js?
我是Node的新手,我真的很困。
我試圖使我的Web服務器在當前目錄中查找文件,並在瀏覽器中將它們顯示為鏈接,以便我可以下載它們。
但是,文件列表只是隨每個請求更新,並一遍又一遍地顯示。 我不能使用任何框架或外部組件,並且已經堅持了兩天。 我確實做了很多研究,嘗試了很多事情,但仍然無法正常工作。
我將在下面添加我最后一次嘗試的代碼,如果有人可以幫助我提供一點點信息,將不勝感激。 謝謝!
var http = require("http");
var fs = require("fs");
var currentServerDir = ".";
var port = 8080;
var content = "";
var server = http.createServer(handlerRequest).listen(8080);
function handlerRequest(request, response) {
fs.readdir(currentServerDir, function getFiles(error, items) {
items.forEach(function getItems(item) {
content += "<br><a href= " + "\" " + item + "\" " + ">" + item + "</a><br>";
});
});
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.write(content);
response.end();
}
編輯:
並從那里借了一些代碼。 現在,我可以單擊一個文件,但是無需下載或查看它,只需說“未定義”即可。
var http = require('http');
var content
function getFiles()
{
fs.readdir(currentServerDir, function getFiles(error, items)
{
items.forEach(function getItems(item)
{
content+= "<br><a href= " + "\" " + item + "\" " + ">" +item + "</a><br>";
});
});
}
http.createServer(function (req, res) {
var html = buildHtml(req);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length,
'Expires': new Date().toUTCString()
});
res.end(html);
}).listen(8080);
function buildHtml(req) {
var header = '';
var body = content;
return '<!DOCTYPE html>'
+ '<html><header>' + header + '</header><body>' + body + '</body> </html>';
};
您的代碼中存在一些問題。
getFiles()
導致永遠不會填充content
getFiles()
content
最終將仍然為空,因為您使用了fs.readdir()
。 這是一個異步函數,在用於構建html頁面之前,將無法填充content
。 您可以通過使用發布的要點AlexS作為對問題的評論來解決前2個問題。 第三個需要更多的設置,但是如果您使用Express,則可以輕松設置。
您可以將download
標簽添加到HTML鏈接中:
items.forEach(function getItems(item)
{
content+= "<br><a href= " + "\" " + item + "\" " + " download>" +item + "</a><br>";
});
如果您不關心瀏覽器支持,則可以使用a
標簽中的download屬性。 看起來像這樣:
<a href="test.html" download="nameOfFileAfterDL">DL me!</a>
受Firefox 14+和Chrome 20+支持
但是,如果您想要一個通用的解決方案,則可以在發送文件之前先對其進行壓縮,據我所知,“單擊它們”時始終會下載.zip。
您可以使用' node-zip或archiver來壓縮文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.