首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用axios和文件编码将多个byteIO文件从Flask端点发送到Vue

如何使用axios和文件编码将多个byteIO文件从Flask端点发送到Vue
EN

Stack Overflow用户
提问于 2022-04-05 06:39:39
回答 1查看 187关注 0票数 0

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的启发):

代码语言:javascript
复制
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

代码语言:javascript
复制
@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文件。

代码语言:javascript
复制
    // 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();
      });
    });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-05 07:56:31

我解决了这个问题。下面的axios请求完成了这个任务。这个问题非常有用:Creating a BLOB from a Base64 string in JavaScript

代码语言: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();
          });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71747257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档