How do I implement a file upload feature using Node.js and express so that the user is prompted to save the file?

Basically I would like to have a button that people could click to export some data. Currently I have connected 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 the file or anything else, the call will succeed.

If I look at the response to the ajax call, it has a JSON that I want to export to it. Here is the code I have provided 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 returning the data quietly?

+3


source to share


1 answer


I wrote a demo app to play with it 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 HTTP headers only, I believe this is browser only. Basically what happens is the function res.attachment

sets the server Content-Disposition

HTTP header <<24>. Some browsers like Firefox call Save As. Chrome and Safari are not default. However, you can change this default behavior in Chrome or Safari preferences. I have not tested in Internet Explorer.

I tried changing Content-Type

to check if this changes the behavior, but it doesn't.

In short, you won't be able to overwrite your users' settings.

You can see more here: How to Force Save As Dialogue When Streaming PDF Attachments

+4


source







All Articles