【问题标题】:Download file from node server on a custom directory in a PC从 PC 中自定义目录上的节点服务器下载文件
【发布时间】:2017-09-26 11:08:56
【问题描述】:

我正在尝试制作一个程序,提示浏览器端的用户从 nodeJS 服务器下载文件。我读到了 expressJS 函数 res.dowload,但我想我在客户端缺少一些东西,因为我没有下载任何文件,也没有提示我去哪里下载。

这是 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>
	$(document).ready(function(){
		$("#ajaxButton").click(function(){
			$.get("index1.html", function(data, status){
				console.log("Data: " + data + "\nStatus: " + status);
				$("#header2").text(data);
			});
		});
		//==
		$("#download").click(function(){
			$.get("index1.html-download", function(data, status){
				console.log("Data: " + data + "\nStatus: " + status);
				$("#header2").text(data);
			});
		});
		//==
	});
</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!");
        }
    });
});

【问题讨论】:

    标签: javascript node.js browser frontend backend


    【解决方案1】:

    你应该使用 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');
    });
    

    【讨论】:

    • 试过了,我在控制台中得到了文件的内容,但是文件没有下载。
    • 您需要Content-disposition 标头。我已经用它修改了代码。
    • 现在我将文件内容作为文本放入新打开的选项卡中。仍然没有下载文件:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2015-11-28
    • 2014-06-02
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    相关资源
    最近更新 更多