2016-05-24 52 views
1

我試圖將一個zip文件(由Flask在內存中創建)提供給JS前端。下載的文件已損壞,我不明白我做錯了什麼。內存中創建的Zip文件已損壞

@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) 
+1

您是否嘗試過使用十六進制編輯器來比較下載的文件與生成的文件? –

+0

@RandomDavis我不確定你的意思,因爲文件是在內存中生成的。 –

+0

添加代碼以在發送之前將'zf'保存到本地文件,然後進行比較。 –

回答