J
J
Jintsuu2018-12-23 19:47:54
Node.js
Jintsuu, 2018-12-23 19:47:54

How to transfer file from node js server to client side?

I transfer to the server what the user typed in the code editor, then I pack it all into a file, and the question is, how can I transfer this file back to the client side so that the user can then download this file?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey, 2018-12-23
@alekstar79

Do you want the user to click on the button and start downloading the file? It is not necessary to transfer the file, in this case, but the headers that initialize the process.

M
Michael, 2018-12-23
@mak_ufo

As I understand it, you do not need to transfer the file. Save the typed text to a file and give the user a link to download it

S
Sergey, 2018-12-24
@yarkin

Your description is pretty general.
From the server side:
1) Data processing takes a little time and the response is expected on the same connection? If the resulting file is in the process memory, then there is nowhere easier - to write data as a response, setting the necessary headers ( Content-Type, Content-Length, Content-Disposition, if required). If on disk, then either read and do as in the previous sentence, or send a link to the file and download it with the next request from the client. Also, if there is nginx in front of the node (other web servers also support this), then you can use a thing called X-Sendfile (so as not to load the node to serve content from disk).
2) If processing takes a long time, then usually the client is immediately answered with some unique request identifier, by which he periodically checks for readiness (if there are no other channels for effective feedback) and receives a download link (which is further processed either by nginx or the same express-static).
From the client side:
1) If the request goes through XHR, then, as far as I remember, you need to use some crutches so that the browser shows the file save dialog to the client (Google is here to help).
2) If the standard form submission and the server immediately responds with a file, then nothing needs to be done at all (the Content-Disposition header may be required, otherwise the browser can display the file if it can read this format itself, plus to set an adequate file name).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question