从PC上的自定义目录下的节点服务器下载文件

问题描述:

我正在试图制作一个程序,提示用户在浏览器端从nodeJS服务器下载文件。我读了expressJS函数res.dowload,但我错过了客户端的东西,我猜,因为我没有得到任何文件下载,也没有提示我在哪里下载。从PC上的自定义目录下的节点服务器下载文件

这里是代码的NodeJS:

var http = require("http") 
var express = require("express") 
var url = require("url") 
var fs = require("fs") 

var app = express(); 

app.get('/', function(req, res) { 
    console.log(req.url); 
    res.sendFile(__dirname + "/index.html"); 
}) 

app.get('/index1.html', function(req, res){ 
    console.log(req.url); 
    res.send("Riko"); 
    //res.sendFile(__dirname + "/index1.html");  
}); 


app.get('/index1.html-download', function(req, res){ 
    console.log(req.url); 
    res.sendFile(__dirname + "/download.txt"); 
}); 


app.listen(80, function(){ 
    console.log('Server running at http://127.0.0.1:80/'); 
}); 

在这里,这是浏览器代码:

<!DOCTYPE html> 
 
<html> 
 
    <body> 
 

 
<p id="demo"/> 
 
<h2 id="header2">Hello</h2> 
 
<button id="ajaxButton">Make a request!</button> 
 
<button id="download">Download</button> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
<script> 
 
\t $(document).ready(function(){ 
 
\t \t $("#ajaxButton").click(function(){ 
 
\t \t \t $.get("index1.html", function(data, status){ 
 
\t \t \t \t console.log("Data: " + data + "\nStatus: " + status); 
 
\t \t \t \t $("#header2").text(data); 
 
\t \t \t }); 
 
\t \t }); 
 
\t \t //== 
 
\t \t $("#download").click(function(){ 
 
\t \t \t $.get("index1.html-download", function(data, status){ 
 
\t \t \t \t console.log("Data: " + data + "\nStatus: " + status); 
 
\t \t \t \t $("#header2").text(data); 
 
\t \t \t }); 
 
\t \t }); 
 
\t \t //== 
 
\t }); 
 
</script></body> 
 
</html>

**** ****编辑

它的工作方式如下:

app.get('/index1.html-download', function(req, res){ 
    console.log(req.url); 
    res.download(__dirname + '/download.txt', 'download.txt', function(err){ 
     if (err) { 
      console.log(err); 
     } 
     else { 
      console.log("File send without errors!"); 
     } 
    }); 
}); 

您应该使用SENDFILE方法:

app.get('/index1.html-download', function(req, res){ 
    console.log(req.url); 
    res.setHeader('Content-disposition', 'attachment; filename=download.txt'); 
    res.sendFile('download.txt') 
}); 

您还可以在新标签中打开文件,而不是仅仅通过AJAX下载:

$("#download").click(function(){ 
    window.open('http://your-site.com/index1.html-download','_blank'); 
}); 
+0

试过,我得到控制台中文件的内容,但该文件未被下载。 – Hairi

+1

您需要比'Content-disposition'标题。我用这个修改了代码。 – Adam

+0

现在我将文件的内容作为文本获取到新打开的选项卡中。仍然没有下载的文件:( – Hairi