How to download a Docx file or msWord file using reactjs?
With "../../testFile.docx"
the app is attempting to serve the file from a relative path from where the app is being hosted and served from. The testFile.docx
file needs to be accessible and served correctly.
If serving file from the public folder
Place
testFile.docx
in thepublic
directory./public
+-/files
+-testFile.docxUse an absolute path to access the
testFile.docx
file.Examples:
Approach 1
const onDownload1 = () => {
saveAs("/files/testFile.docx", "testFile.docx");
};Approach 2
const onDownload2 = () => {
fetch("/files/testFile.docx").then((response) => {
response.blob().then((blob) => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement("a");
a.href = url;
a.download = "testFile.docx";
a.click();
});
});
};
If imported and used locally
import file from './testFile.docx';
Approach 3
const onDownload3 = () => {
saveAs(file, "testFile.docx");
};Approach 4
const onDownload4 = () => {
fetch(file).then((response) => {
response.blob().then((blob) => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement("a");
a.href = url;
a.download = "testFile.docx";
a.click();
});
});
};
How do I download file from public folder in React using Express
I think you don't need the form at all, try something like this instead:
<Fragment>
<div className="row">
<a
href="http://localhost:5000/download"
target="_blank"
className="container col-3"
>
<button className='btn btn-primary btn-block mt-4'/>
</a>
</div>
</Fragment>
In the href
attribute I assume you have your server listening on port 5000, you may change it to point to your server.
Also try the behavior without the target
attribute, you might not need it
Related Topics
Moment Js Get First and Last Day of Current Month
Instead of Downloading, Files Are Opening in Browser
How to Save Binary Buffer to Png File in Nodejs
Javascript: Location.Href to Open in New Window/Tab
Angular 2 Concatenate Variable in Interpolation
How to Close Toggle Menu When Clicking Navigation Item Anchor Link
Show Base64 Pdf Data Using Window.Open on Chrome New Version
What Does This Format Means T00:00:00.000Z
Clear an Input Field With Reactjs
How to Style HTML Select Option Hover and Selected Option Effects
Regex With Space and Letters Only
To Get a Popup Message After Submit
Check Whether an Input String Contains a Number in JavaScript
How to Convert File to Base64 in JavaScript