Reputation: 85056
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.
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?
Upvotes: 3
Views: 7112
Reputation: 39395
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"
}
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.
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.
You can see more here: How to force a Save As dialog when streaming a PDF attachment
Upvotes: 4