Answer the question
In order to leave comments, you need to log in
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);
});
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); /*Добавление параграфа в документ*/
/*Отправка файла*/
});
});
Answer the question
In order to leave comments, you need to log in
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;
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 questionAsk a Question
731 491 924 answers to any question