0

I am trying to create a button on my website that will allow a user to downlaod a .csv file. I currently have the site hit the server and the server generates a string of text which is in the format of a csv file. I am not sure where to proceed. Do i save this string to a file on the server and then send the file to the client (I would prefer not to create files on the server side) or do i send the client the string of text and then create the file on the client side? I would like the button to function as a user would expect a download button to work (ie a they are given a choice as to where to save the file and a progress bar shows the progress f the file download)

I am using Nodejs and express on the server side.

lufthansa747
  • 1,923
  • 3
  • 26
  • 39

2 Answers2

0

Once the file is generated just put a link to the file location in your page:

<a href="filename.xxx" target="_blank">Clickable text</a>

The browser will know how to handle this and prompt the user where they would like to save the file. Once the user specifies this the file will be downloaded to the user's computer.

If you want to just create the file in memory and then send it to the user you could do something like this if you are using asp.net MVC:

public FileStreamResult MyFunction(/*your parms*/)
{
    System.IO.MemoryStream stream = FunctionThatCreatesMyCalendarStream();
    //you may need stream.Position = 0 here depending on what state above funciton leaves the stream in.
    //stream.Position = 0;
    FileStreamResult result = new FileStreamResult(stream, "text/csv");
    result.FileDownloadName = "myfiledownloadname.csv";
    return result;
} 

EDIT: If you are using node.js look at this post - Nodejs send file in response

Community
  • 1
  • 1
Jason Roell
  • 6,679
  • 4
  • 21
  • 28
0

This is a callback function that I currently use to send a csv. You can put the button so that it calls this function, and sends the csv. when you call this service, automatically downloads a file to your compurer.

function(req,res){
    // Process that does the csv and stores it in a variable csv_variable
    res.writeHead(200,{'content-type':'text/csv'});
    res.write(csv_variable);
    res.end();
});

Hope this helps!

Skalas
  • 63
  • 7
  • and what is the name of the file to download? – jdnichollsc Dec 29 '15 at 20:16
  • 1
    It renames it to the path selecter in the router. e.g. ```{javascript} router.get('/csv1', function(req,res){ z='1,1,1,1,1,1' res.writeHead(200,{'Content-Type': 'text/csv; charset=utf-8'}); res.write(z); res.end(); }) ``` Gives the name **csv** While if you change the route to csv1. It will change the name to csv1 – Skalas Dec 30 '15 at 21:48