如何使用Node.js和express实现文件下载功能,以便提示用户保存文件? [英] How to implement file download functionality using Node.js and express, so that the user is prompted to save the file?

查看:236
本文介绍了如何使用Node.js和express实现文件下载功能,以便提示用户保存文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我希望有一个按钮,人们可以单击该按钮来导出一些数据.目前,我已经将其挂接到一个ajax调用上,该调用会击中服务器上获取数据的一些代码.不幸的是,从来没有提示用户保存文件或任何东西,只是成功地进行了呼叫.

Basically I would like to have a button that people could click to export some data. Currently I have this hooked up to an ajax call that hits some code I have on the server to get the data. Unfortunately the user is never prompted to save a file or anything, the call is just successfully made.

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

If I look at the response to the ajax call it has the JSON that I want to export in it. Here is the code I have come up with so far:

#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')

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

Any suggestions to get this to prompt the user to save the file rather than just quietly returning the data?

推荐答案

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

I wrote a demo app to play with this a bit:

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中进行测试.

With just HTTP headers, I believe this is just browser specific. Essentially, what's going on is the res.attachment function is setting the Content-Disposition HTTP server header to attachment. Some browsers such as Firefox prompt you to "Save As". Chrome and Safari don't by default. However, you can change this default behavior in the options of either Chrome or Safari. I did not test in Internet Explorer.

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

I tried changing the Content-Type to see if that would override any behavior, but it doesn't.

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

In short, you're not going to be able to overwrite your users' settings.

您可以在此处看到更多信息:在流式传输PDF附件时如何强制另存为"对话框

You can see more here: How to force a Save As dialog when streaming a PDF attachment

这篇关于如何使用Node.js和express实现文件下载功能,以便提示用户保存文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆