Zip file is invalid from Flask send_fiile

330 Views Asked by At

I'm very new to JS code and just take over left work from colleague.

When Flask code return zip file using send_file, the JS side download seems invalid. Other format, like text and csv are good.

The Server code snippet:

@bp.route('/download_file', methods=['POST'])
@login_required
def download_file():
    download_path = request.form.get("download_path")
    if os.path.exists(download_path):
        @after_this_request
        def send_response(response):
            return response
        return send_file(download_path, as_attachment=True)

The download path is file path located on my server

Blockquote

The JS code is below, the goal is user click the download button and file is downloaded.

$.post('/download_file', {'download_path' : download_path}).done(function(data) {
  var blob =new Blob([data]);
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = "my.zip";
  link.click();
}).fail(function(data) {
  alert("danger", "Can't find download file");
});

Zip file is able to download but it's corrupted. My limit frontend debug experience shows data in Blob looks weird. Appreciate any help and suggestions

enter image description here

1

There are 1 best solutions below

1
On

It could be the content type that is missing in the response:

response.headers['Content-Type'] = 'application/pdf'