0

I'm trying to respond with a docx file to the browser so a client can preview it.
Here are two ways I tried:

const rs = fs.createReadStream(fullPath);
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
rs.pipe(res);
const file = await fs.readFile(fullPath); // this time fs is imported from fs/promises
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
res.status(200).send(file);

The problem is that both methods are triggering a download. Instead, what I want is to preview the file. On MS Edge if you open this dummy docx file it will redirect you to a web version of MS word to be able to preview it. However it is possible to view the file in an iframe as shown in this question. However when I provide my api url the iframe says it cannot open the file most probably because my server is not responding with the file appropriately. On the other hand, when giving the iframe this url the document displays correctly.
So the question is: How to send the file from the server without triggering a download but preiview it?

  • When I load the URL you gave in an iframe, my browser (Chrome) nevertheless downloads it. It seems a decision of the browser whether to download resources of that content type, this cannot be influenced by the server. – Heiko Theißen Dec 30 '22 at 17:10

1 Answers1

0

To preview a file from the server without triggering a download, you can set the Content-Disposition header to inline. This suggests to the browser that the content should be displayed within the browser. This will usually only work if the browser knows how to handle the document type:

res.setHeader("Content-Disposition", "inline");

References: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition