'Downloading a docx file via react.js
Hi i have been trying to download a word file via react.js but when i press submit and it downloades it cant open the word file. The console.logs looks completely fine. If i open the file in notepad it just says readablestream. All help appreciated
onSubmit = () =>{
let data = {data: this.state}
console.log(data)
console.log(JSON.stringify(data))
fetch(this.state.endpoint,{method: 'post', headers: {"Content-Type": "application/json"}, body: JSON.stringify(data)}).then((response) =>{
var blob = new Blob([response], {"Content-type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
saveAs(blob, "dynamic.docx")}
)
Solution 1:[1]
I'd rather use response.blob()
I tried it with ExpressJs server:
app.post(url, (req, res) => {
try {
const { name } = req.body
res.status(200).sendFile(__dirname + "/" + name)
} catch (e) {
console.log("req/res", e)
}
})
and React:
add preventDefault to onSubmit
made custom saveAs()
used response.blob()
const saveAs = (blob, name) => { const downloadUrl = window.URL.createObjectURL(blob) const a = document.createElement("a") a.href = downloadUrl a.download = name a.click() } const onSubmit = e => { e.preventDefault() fetch("http://localhost:5000/getfile", { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }).then(response => { response.blob().then(blob => { saveAs(blob, "test.docx") }) }) }
Hope something of this will help, happy coding:)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ipa Stor |