Send text as a download file

An attempt to send a simple text string as a file loaded under a specific name upon request. It doesn't seem to be able to figure out why this code does not work.

var text_ready = "This is a content of a txt file." res.setHeader('Content-type', "application/octet-stream"); res.setHeader('Content-disposition', 'attachment; filename=file.txt'); res.send( new Buffer(text_ready) ); 

When this code is executed, I get only an XHR response (with this line as content), but the download does not start. But I expected that getting this response would force the browser to download the file with file.txt as a name having the contents of the line above.

How to fix it? What am I doing wrong?

Perhaps this will be important: working in Chrome 41 on Windows.

EDIT: It seems that I should describe a little deeper. The workflow is as follows:

  • contains table cells with angular ng-click events attached to each of them
  • when you click on a GET request on "/ download" using jQuery $ .get ("/ download")
  • the server has a route to handle these GET requests.
  • I need to ensure that a specific text string is sent to the user and saved as a file (so that the download starts when clicked, briefly)

Testings

  • works when I navigate manually to this url by typing that url into the address bar and pressing enter
  • it doesn’t work when I click on this cell - the request is sent, the response is received, but the download does not start.
+6
source share
1 answer

Tested on my node.js version 0.12.2, Windows 7, Chrome and Firefox

 var http = require('http'); http.createServer(function (req, res) { var text_ready = "This is a content of a txt file." res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=file.txt'}); res.end( text_ready ); }).listen(8080, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8080/'); 

I think you are not using the latest version of node.js. Perhaps you can change the Content-type header, which may work. Alternatively, you can use res.end( new Buffer(text_ready) ); . I tested it.

Editorial: How to download a file from node.js with javascript call (jQuery onclick):

JavaScript:

 <script type="text/javascript"> $(document).ready(function(){ $("#button").on('click',function(){ window.location = 'http://127.0.0.1:1337/'; }); }); </script> 

HTML:

<button id="button">Download</button>

I'm sure you know how to rewrite jQuery to angularJS. :) I think this is better than using an Ajax call. If you really need Ajax, I will learn how to do it.

+8
source

Source: https://habr.com/ru/post/984934/


All Articles