【发布时间】: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