Flask send_file() function downloads invalid archive from browser

I’m designing a database website where users can search for and download simple text-based files. The backend is Flask (also handles REST) + MongoDB.

I have built functions on the frontend to let user select a few filenames to be fetched from the server, to then add them to an archive and download the archive as a .zip file. Once the archive gets downloaded, I find that all zipfile handling programs report that the file is not an archive.

The text-based files can currently be directly downloaded from the browser one file at a time. I’m leveraging this function to pass the files in a for loop instead to write them into the archive one at a time. So, I have verified that the correct files are fetched each time and a correct filename is assigned to each file. My suspicions are with the way the files are written into the archive and the way the archive is transferred to the browser for download. My suspected problematic code snippet from my python script is below:

import io
import zipfile
from flask import Flask, Response, session, request, make_response, send_file

def download_selection(self):
        files = request.json['files'] #
        archive = io.BytesIO() #since bytesIO is one of the supported formats of archive for send_file()

        with zipfile.ZipFile(archive, 'w') as zipf:
            for file in files: #file is a dictionary
                fs_id = file['fileID'] #id of file to be fetched from backend
                filename = file['filename'] #name to be assigned to the fetched file
                try:
                    mfile = self._db.get_magres_file(fs_id) #currently working routine to correctly fetch one file from the server
                    if isinstance(mfile, bytes): #check that the file type is correct
                        zipf.writestr(f"{filename}.magres", mfile) #.magres is the text-based file format we use; I use writestr() to write the file into the archive
                    else:
                        print(f"Invalid file content for {fs_id}: {mfile}")
                        continue
                except MagresDBError as e:
                    # Handle error
                    print(f"Error retrieving file {fs_id}: {e}")
                    continue
        
        archive.seek(0)

        return send_file(archive, mimetype='application/zip', as_attachment=True, download_name='selected_files.zip')
  1. I have printed out variable types and contents to the terminal when running at each stage. The contents are what I expect them to be.
  2. I have tried the download with different web browsers, so the problem is not in the way the browser handles the archive or corrupts it.
  3. send_file() returns the zipfile to download. The zip file cannot be opened as an archive, but for some reason when I open it using a text editor, I see contents of the test files I fetched from the backend written one below the other as one long file with some strange text header preceding each file contents like in the picture below:
    strange text header
  4. I have tried replacing the send_file function by make_response as below, with the same outcome:
resp = make_response(archive)
resp.headers['Content-Type'] = 'application/zip'
resp.headers['Content-Disposition'] = 'attachment; filename=selected_files.zip'
return resp, self.HTTP_200_OK
  1. In the code where one file is directly sent to browser for download, the ‘mfile’ is directly returned as:
resp = make_response(mfile)
resp.headers['Content-Type'] = 'text/plain'
resp.headers['Content-Disposition'] = 'attachment'

return resp, self.HTTP_200_OK
  1. I have referred to this stackoverflow post and adapted by return code using response instead of send_file or make_response, but I have the same outcome as before – zip file is not an archive and could not be opened.
    Changed code:
    return Response(archive.getvalue(),
    mimetype=’application/zip’,
    headers={‘Content-Disposition’: ‘attachment;filename=selected_files.zip’}), self.HTTP_200_OK
  2. I also tried adding a zipf.close() after adding the contents to the archive. This has not changed the outcome.

Could anyone please advise what might be a problem here? Please let me know if I could provide more useful information that might help.

New contributor

Sathya-S3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật