TL;DR
烧瓶:
docx -> bytesIO -encodebytes() --> 字节--decode()-> string ->数组包含多个这些字符串。
Vue:
包含这些字符串的数组---> blob
问题
我正在尝试一次将多个byteIO文件从Flask端点返回到Vue应用程序。
基于this SO question,可以使用bytesencode()和.decode()将byteIO文件转换为字符串。然后将字符串附加到数组并序列化json。
但是,我不知道如何将Vue中的凸起反转回必要的blob对象(该对象将被下载)。
对于如何做到这一点,有什么建议吗?
如何从docx模板创建我的bytesIO文档文件(我的代码很大程度上受到了snakecharmerb's answer in this post的启发):
def from_template_multiple(context): # context is a dict containing custom attributes to be rendered in the document
template = DocxTemplate(template_document.docx')
# Create in-memory buffer
target_file = BytesIO()
# Render template and save to the buffer
template.render(context)
template.save(target_file)
# Reset the buffer's file-pointer to the beginning of the file
target_file.seek(0)
# return target file instead of send_file directly
return target_file我的烧瓶路由,接收从Vue接收上下文属性的axios调用。文件编码部分来自this answer。
@hagis_api_bp.route('/docx/multiple', methods=['POST'])
def generate_word_multiple():
request_json = request.get_json()
# array to store blob derivations
blob_array = []
for item in request_json['body']:
context = json.loads(item)
target_file = process.from_template_multiple(context)
# encode as base64
from base64 import encodebytes
encoded_file = encodebytes(target_file.getvalue()).decode('ascii')
# append target file to blob array
blob_array.append(encoded_file)
return jsonify({'result': blob_array})最后是Vue部分。这个axios调用用于发送上下文信息(json),这里我希望返回blob_array,然后恢复编码过程以接收“原始”blob文件。
// axios request + file download
axios({
url: 'docx/multiple',
data: {body: body_array},
method: 'POST',
}).then((response) => {
// looping over each element in response.data (each converted bytesIO string)
response.data['result'].forEach((element) => {
// convert string to blob here ?
// download blob as docx file
const url = window.URL.createObjectURL(new Blob([converted_element])); // --> using result from missing conversion above
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'title.docx');
document.body.appendChild(link);
link.click();
});
});发布于 2022-04-05 07:56:31
我解决了这个问题。下面的axios请求完成了这个任务。这个问题非常有用:Creating a BLOB from a Base64 string in JavaScript
// axios request + file download
axios({
url: 'docx/multiple',
data: {body: body_array},
method: 'POST',
}).then((response) => {
response.data['result'].forEach((element) => {
console.log(element)
// decode string to blob --> solution to question
const byteCharacters = atob(element);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
console.log(byteArray)
const url = window.URL.createObjectURL(new Blob([byteArray]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'test.docx');
document.body.appendChild(link);
link.click();
});
});https://stackoverflow.com/questions/71747257
复制相似问题