【问题标题】:Flask - Problems with Sending Zipped Folder Back To UserFlask - 将压缩文件夹发送回用户的问题
【发布时间】:2020-02-09 19:18:48
【问题描述】:

我正在尝试将一个 excel 文件发送回用户浏览器的压缩文件夹中。

我使用 openpyxl 构建 excel 文件,这是我的代码:

@app.route('/test', methods=['GET', 'POST'])
    def test():

        # ...

        from zipfile import ZipFile

        # ...        

        buf = BytesIO()
        wb.save(buf)
        buf.seek(0)

        with ZipFile(buf, 'w') as myzip:
            myzip.write(buf, arcname='test.xlsx')

        return send_file(myzip, attachment_filename='folder.zip', as_attachment=True)

但是,我收到以下错误:

TypeError: stat: path 应该是字符串、字节、os.PathLike 或整数,而不是 _io.BytesIO

如何在不使用 bytesio 对象的情况下做到这一点?或者我可以修改代码以便它可以容纳一个 bytesio 对象吗?

非常感谢。

【问题讨论】:

    标签: python flask zipfile stringio bytesio


    【解决方案1】:

    试试这个代码。

    @app.route('/test', methods=['GET', 'POST'])
        def test():
    
            # ...
    
            from zipfile import ZipFile
    
            # ...        
    
            buf = BytesIO()
            wb.save(buf)
            buf.seek(0)
    
            filename = 'folder.zip' # assuing zip file u need
            with ZipFile(filename, 'w') as myzip:
                myzip.writestr(zinfo_or_arcname='test.xlsx', bytes=buf.read())
    
            return send_file(myzip, attachment_filename='folder.zip', as_attachment=True)
    

    更改,使用writestr 而不是write

            filename = 'folder.zip' # assuing zip file u need
            with ZipFile(filename, 'w') as myzip:
                myzip.writestr(zinfo_or_arcname='test.xlsx', bytes=buf.read())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多