在内存中创建的 Zip 文件已损坏
In-memory created Zip file is corrupted
我正在尝试向 JS 前端提供一个 zip 文件(由 Flask 在内存中创建)。下载的文件已损坏,我不明白我做错了什么。
@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)
正如评论中指出的那样,Python 部分工作得很好。修复 JS 部分的解决方案是添加
responseType: 'arraybuffer'
在 http 请求的参数中。
参考:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
我正在尝试向 JS 前端提供一个 zip 文件(由 Flask 在内存中创建)。下载的文件已损坏,我不明白我做错了什么。
@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)
正如评论中指出的那样,Python 部分工作得很好。修复 JS 部分的解决方案是添加
responseType: 'arraybuffer'
在 http 请求的参数中。
参考:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data