通过react.js下载docx文件



嗨,我一直试图通过react.js下载一个word文件,但当我按下submit并下载时,它无法打开word文件。console.log看起来完全不错。如果我打开记事本中的文件,它只显示readablestream。所有帮助感谢

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")}
)

我宁愿使用response.blob((

我在ExpressJs服务器上尝试过:

app.post(url, (req, res) => {
try {
const { name } = req.body
res.status(200).sendFile(__dirname + "/" + name)
} catch (e) {
console.log("req/res", e)
}
})

和React:

  • 将preventDefault添加到onSubmit

  • 制作自定义saveAs((

  • 已使用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")
    })
    })
    }
    

希望这会有所帮助,愉快的编码:(

最新更新