繁体   English   中英

在node.js中单击时,如何使这些链接下载文件?

[英]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();
 }

编辑:

我跟随Node.js生成HTML

并从那里借了一些代码。 现在,我可以单击一个文件,但是无需下载或查看它,只需说“未定义”即可。

    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>';
    };

您的代码中存在一些问题。

  1. 您永远不会调用getFiles()导致永远不会填充content
  2. 如果您调用getFiles() content最终将仍然为空,因为您使用了fs.readdir() 这是一个异步函数,在用于构建html页面之前,将无法填充content
  3. 您对服务器的每个请求都以相同的方式处理,因此您将无法下载任何文件,因为您将始终只显示页面。

您可以通过使用发布的要点AlexS作为对问题的评论来解决前2个问题。 第三个需要更多的设置,但是如果您使用Express,则可以轻松设置。

您可以将download标签添加到HTML链接中:

items.forEach(function getItems(item)
{
   content+= "<br><a href= " + "\" " + item + "\" " + " download>" +item +        "</a><br>";
});

MDN参考

如果您不关心浏览器支持,则可以使用a标签中的download属性。 看起来像这样:

<a href="test.html" download="nameOfFileAfterDL">DL me!</a>

受Firefox 14+和Chrome 20+支持

但是,如果您想要一个通用的解决方案,则可以在发送文件之前先对其进行压缩,据我所知,“单击它们”时始终会下载.zip。

您可以使用' node-ziparchiver来压缩文件。

暂无
暂无

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

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