C
C
CarpKoi2018-11-12 20:22:48
JavaScript
CarpKoi, 2018-11-12 20:22:48

How to send a file generated on the server and download it on the client?

The HTML page contains a form, the data from which is sent to the server via client-side JS. On the server, the data is processed, and based on their values, a specific docx file is created. This generated file is sent back to the client for download.
The client and server parts are written in JavaScript. The DOCX.js module is used to create a document on the server .
Client side:

$(document).on('click', '#btnCreate', function (event) {
  event.preventDefault();
  
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/postCreateDoc', true);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.onload = function(){
    /*Обработка полученного файла, отправка файла на загрузку*/
  };
  var kindDoc = $('#typeDoc').val(); /*Получение данных из Select*/
  var userName = $('#userName').val(); /*Получение данных из Input*/
  var data = JSON.stringify([kindDoc, userName]);
  xhr.send(data);
});

Server part:
var docx = require('docx');
var express = require('express');
var app = express();

/*Обработка других запросов*/

app.post('/postCreateDoc', function(req,res){
    const chunks = [];
    req.on('data', chunk => chunks.push(chunk));
    req.on('end', () => {
        var data = Buffer.concat(chunks);
        data = JSON.parse(data);
        /*Обработка полученных данных*/
        /*Для примера привожу создание абзаца в WORD-документе:*/
        var doc = new docx.Document(); /*Создание документа*/
        var p1 = new docx.Paragraph('Текст-текст-текст-текст'); /*Создание параграфа(абзаца) с текстом*/
        doc.addParagraph(p1); /*Добавление параграфа в документ*/
        /*Отправка файла*/
    });
});

I am directly interested in the questions: what code should be written in the server part in order to send the generated docx file to the client, and what code should be written in the client part in order to send this file for download . Not necessarily examples with .doc(x) format files... I think examples with regular .txt files will do as well.
---
Created a .doc file through XAML and HTML. The problem is that when this document was subsequently modified on the computer, the <document name>.files folder with XAML files was created in the directory. For this reason I use the module in the server part.
Creating a document on the client side, like hereI do not consider. I just gave as an example such a simple code for creating a file.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2018-11-12
@CarpKoi

Send the correct headers, that's enough.
I'm not strong in node, in php something like this:

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
 header('Cache-Control: no-store, no-cache, must-revalidate');
 header('Cache-Control: post-check=0, pre-check=0', FALSE);
 header('Pragma: no-cache');
 header('Content-transfer-encoding: binary');
 header('Content-Disposition: attachment; filename=some.docx');
 header('Content-Type: application/msword');
 echo $contentOfWordDoc;

what is it for and why?
The problem is that when this document was subsequently modified on the computer, the <document name>.files folder with XAML files was created in the directory.
when saving such a file by default, Word tries to save it as html, just set the type of document you need in the type selector when saving (docx for example).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question