下载使用VueJS在Flask中创建的docx文件

zbwhf8kr  于 2023-10-23  发布在  Vue.js
关注(0)|答案(1)|浏览(136)

我想知道如何在VueJS中下载docx文件。我最初试图在前端创建它,但文件最终被损坏,所以我使用flask创建docx文件(当我保存本地打开刚刚好),然后将其发送到前端,我想下载它,但文件最终被损坏。
对于Flask API,这是我用来创建文件的:

def download_docx():
    try:
        data = request.get_json()
        write_to_docx = data.get('docxData')
        document = Document()
        new_parser = HtmlToDocx()
        new_parser.add_html_to_document(write_to_docx, document)
        docx_file = BytesIO()
        file_name = "test.docx"
        document.save(docx_file)
        docx_file.seek(0)
        return send_file(docx_file,
                             attachment_filename=file_name,
                             as_attachment=True,
                             mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                             cache_timeout=0)
    except Exception as e:
        print(traceback.print_exc())
    return render_template('index.html')

对于VueJS方面,我有:

export function downloadDocx(token, data) {
  const headers = authHeader(token)
  return mainAxios.post(`${API_URL}/download/docx`, data, { headers })
}


downloadDocx() {
      
      let data = {
        docxData: this.fullHtml
      }
      this.$store.dispatch('downloadDocx', data)
      .then(response => {
        if (response.data && response.status == 200) {
          const blob = new Blob([ response.data ], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })
          const url = URL.createObjectURL(blob);
          var element = document.createElement('a');
          element.setAttribute('href', url);
          element.setAttribute('download', 'test.docx');
          element.style.display = 'none';
          document.body.appendChild(element);
          element.click();
          document.body.removeChild(element);
        }
        else {
          console.log("FAILED")
        }
      })
    }
w1jd8yoj

w1jd8yoj1#

你能试试这个吗,看看它是否有效。

downloadDocx() {
    let data = { docxData: this.fullHtml }
    this.$store.dispatch('downloadDocx', data)
        .then((resp) => (resp.status === 200 ? resp.blob() : Promise.reject('something went wrong')))
        .then((blob) => {
            const url = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.setAttribute('download', "true")
            a.style.display = 'none'
            a.href = url
            a.download = 'test.docx'
            document.body.appendChild(a)
            a.click()
            window.URL.revokeObjectURL(url)
        })
        .catch(() => alert('Cannot download the file'))
}

另一种选择是使用FileSaver.jshttps://github.com/eligrey/FileSaver.js)。

相关问题