flask大文件下載解決方案

flask大文件下載解決方案

文件數據小的話,可以直接使用flask自帶的send_file()
讀取文件或者直接寫入緩衝區,再去讀取都可以,StringIO, ByteIO,這樣就是能寫成不生層本地文件去下載的模式了

@app.route('download')
def download():
    file_hash = request.args.get('file')
    if file_hash:
        file = File.by_hash(file_hash)
        path = os.path.join('./output', '{}.csv'.format(file.filename.split('.')[0]))
        def file_send():
            store_path = path
            with open(store_path, 'rb') as targetfile:
                while 1:
                    data = targetfile.read(20 * 1024 * 1024)  # 每次讀取20M
                    if not data:
                        break
                    yield data

        response = Response(file_send(), content_type='application/octet-stream')
        response.headers["Content-disposition"] = 'attachment; filename=%s.csv' % file.filename.split('.')[0]  # 如果不加上這行代碼,導致下圖的問題
        return response
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章