1

I am trying to figure out, if its possible to create a file without storing it in the drive, for only purpose to download it right away within POST request.

const specialRequests = async (req, res, next) => { // POST request
    ... // processing
    let xmlString = ... // get processed xml string

    // create xml file from that xmlString 
    // initialise download of the file, dont save it
    let file = ???
    res.download(file);
};

If its possible how it can be done

Mevia
  • 1,517
  • 1
  • 16
  • 51

1 Answers1

2

The download method is explicitly designed to transfer "the file at path".

You can create a download with some data, but you can't use that method.

res.set('Content-Type', 'text/xml');
res.set('Content-Disposition', 'attachment; filename="example.xml"')
res.send(xmlString);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • indeed its working, but on the client side, file download doesnt start, is there a way to trigger file download by setting some extra headers? – Mevia Mar 17 '20 at 08:22
  • @Mevia — https://i.imgur.com/3UQpu2p.gif — The file download starts when I test it. There must be something else wrong with your code. – Quentin Mar 17 '20 at 08:26
  • yes yes, all working, i was executing it as POST request using fetch, while when converted to GET request its working perfectly, thank you – Mevia Mar 17 '20 at 08:47
  • It's the "using fetch" part that's your problem. You're explicitly handling the response with JavaScript and not with the browser's default handling that you'd get if you navigated to it. If you want to save a file with the data in the response to an ajax request then you need to write JavaScript to do it: https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – Quentin Mar 17 '20 at 08:49