Sunday 19 August 2018

Generating file w/ ExcelJS, sending it to server, and initiating client-side download prompt?

Hello,I am working with the ExcelJS module to generate an Excel file, but am having difficulty achieving the desired flow.What I'd like to have is:User clicks a button on the front-end (built with React) to download an Excel file. This triggers a fetch('/downloads/results') which is the back-end endpoint for the file creation and serving.The file is generated and gets sent to /downloads/results as the res of the get request.The user gets a download prompt from the browser on the front-end so they can decide where to save it.What is happening now is that instead of the user being prompted on the front-end, Node is just creating the Excel file in the same folder as the server file. The bit of code that is creating the file is "workbook.xlsx.writeFile('Project.xlsx')"My current code is below.Relevant server-side code block:function generateSpreadsheet(req, res) { const workbook = new Excel.Workbook(); workbook.creator = 'Project'; workbook.created = new Date(); const worksheet = workbook.addWorksheet("Definitions"); worksheet.columns = [ { header: 'Word', key: 'word', width: 36 }, { header: 'Definition', key: 'def', width: 120 } ]; worksheet.addRows(storedResults); workbook.xlsx.writeFile('Project.xlsx'); } app.get('/downloads/results', (req, res) => { try { generateSpreadsheet(); } catch(err) { console.log(err); } }) Relevant front-end code:renderDownloadButton() { if (this.state.queriesList.length > 0) { return ( ) } } download() { fetch('/downloads/results'); } I've been researching most of yesterday and today but haven't come to a satisfactory answer. I found one somewhat similar question on Stackoverflow where someone mentioned that the front and back ends were on different ports and that was causing the break with no indication of a download on the front-end; in my case, after reading that, I tried accessing the back-end server directly and the browser showed the file being downloaded, but there was still no prompt for the user to decide where to save it.I tried playing around with having the generateSpreadsheet function return a stream, thinking I could then pipe that to the res in app.get but I was getting tripped up a bit.Thanks for any insight/direction you can provide!

Submitted August 20, 2018 at 02:58AM by DWDevDW

No comments:

Post a Comment