我想知道如何在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")
}
})
}
1条答案
按热度按时间w1jd8yoj1#
你能试试这个吗,看看它是否有效。
另一种选择是使用
FileSaver.js
(https://github.com/eligrey/FileSaver.js)。