【问题标题】:How to implement file download functionality using Node.js and express, so that the user is prompted to save the file?如何使用 Node.js 和 express 实现文件下载功能,从而提示用户保存文件?
【发布时间】:2013-02-14 19:14:28
【问题描述】:

基本上我想要一个按钮,人们可以点击它来导出一些数据。目前,我已将此连接到一个 ajax 调用,该调用会命中我在服务器上的一些代码以获取数据。不幸的是,从未提示用户保存文件或任何内容,只是成功进行了调用。

如果我查看对 ajax 调用的响应,其中包含我想要导出的 JSON。这是我到目前为止提出的代码:

#exportData is just a function that gets data based off of a surveyId
@exportData req.body.surveyId, (data) ->
    res.attachment('export.json')
    res.end(JSON.stringify(data),'UTF-8')

有什么建议可以提示用户保存文件而不是简单地返回数据?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    我写了一个演示应用来玩这个:

    app.js

    var express = require('express')
      , http = require('http')
      , path = require('path')
      , fs = require('fs')
    
    var app = express();
    
    var data = JSON.parse(fs.readFileSync('hello.json'), 'utf8')
    
    app.get('/hello.json', function(req, res) {
      res.attachment('hello.json')
      //following line is not necessary, just experimenting
      res.setHeader('Content-Type', 'application/octet-stream')
      res.end(JSON.stringify(data, null, 2), 'utf8')
    })
    
    http.createServer(app).listen(3000, function(){
      console.log('Listening...')
    });
    

    hello.json

    {
      "food": "pizza",
      "cost": "$10"
    }
    

    仅使用 HTTP 标头,我相信这只是特定于浏览器的。从本质上讲,res.attachment 函数将Content-Disposition HTTP 服务器标头设置为attachment。某些浏览器(例如 Firefox)会提示您“另存为”。 Chrome 和 Safari 默认不支持。但是,您可以在 Chrome 或 Safari 的选项中更改此默认行为。我没有在 Internet Explorer 中进行测试。

    我尝试更改 Content-Type 以查看是否会覆盖任何行为,但不会。

    简而言之,您将无法覆盖用户的设置。

    你可以在这里看到更多:How to force a Save As dialog when streaming a PDF attachment

    【讨论】:

      猜你喜欢
      • 2011-09-30
      • 2016-10-03
      • 2015-07-09
      • 2015-02-10
      • 2011-04-29
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      相关资源
      最近更新 更多