【问题标题】:In-memory created Zip file is corrupted内存中创建的 Zip 文件已损坏
【发布时间】:2016-05-24 15:10:28
【问题描述】:

我正在尝试将 zip 文件(由 Flask 在内存中创建)提供给 JS 前端。下载的文件已损坏,我不明白我做错了什么。

@app.route('/route')
def test_zip():
    zf = BytesIO()
    with zipfile.ZipFile(zf, 'w') as archive:
        archive.writestr("test.csv", "test, 2")
    zf.seek(0)
    return send_file(
        zf,
        attachment_filename='test.zip',
        mimetype='application/x-zip-compressed',
        as_attachment=True
    )
$http({
    url: settings.BACKEND_URL + "/route"
}).success(function (data) {
    var anchor = angular.element('<a/>');
    var blob = new Blob([data], {'type': 'application/zip'});
    anchor.attr({
         href: window.URL.createObjectURL(blob),
         target: '_blank',
         download: 'test.zip'
    })[0].click();
}) 

我得到的错误(在 Mac OS X 上)如下:

26 extra bytes at beginning or within zipfile
  (attempting to process anyway)
error [test.zip]:  start of central directory not found;
  zipfile corrupt.
  (please check that you have transferred or created the zipfile in the
  appropriate BINARY mode and that you have compiled UnZip properly)

【问题讨论】:

  • 您是否尝试过使用十六进制编辑器来比较下载的文件和生成的文件?
  • @RandomDavis 我不确定你的意思,因为文件是在内存中生成的。
  • 添加代码以在发送之前将zf 保存到本地文件中,然后进行比较。
  • @JohnGordon 对不起,我忘了提到如果我先将文件存储在文件系统中,那么一切正常。我想了解的实际上是当我试图将所有内容都保存在内存中时出了什么问题。
  • python 部分对我有用。成功函数中的数据是什么?

标签: javascript python angularjs flask zipfile


【解决方案1】:

正如 cmets 中所指出的,Python 部分工作得很好。修复 JS 部分的解决方案是添加

responseType: 'arraybuffer'

在 http 请求的参数中。

参考:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

【讨论】:

    猜你喜欢
    • 2014-11-16
    • 2015-07-25
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    相关资源
    最近更新 更多