Search code examples
pythondjangodjango-viewsdjango-2.2

Error opening photos stored in zip file in Django


I'm going to create a zip file from some of the image files stored on my server. I've used the following function to do this:

def create_zip_file(user, examination):
    from lms.models import StudentAnswer
    f = BytesIO()
    zip = zipfile.ZipFile(f, 'w')
    this_student_answer = StudentAnswer.objects.filter(student_id=user.id, exam=examination)

    for answer in this_student_answer:
        if answer.answer_file:
            answer_file_full_path = answer.answer_file.path
            fdir, fname = os.path.split(answer_file_full_path)
            zip.writestr(fname, answer_file_full_path)
    zip.close()  # Close
    zip_file_name = "student-answers_"+ str(examination.id)+"_" + str(user.id) + "_" + date=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M") + '.zip'
    response = HttpResponse(f.getvalue(), content_type="application/x-zip-compressed")
    response['Content-Disposition'] = 'attachment; filename=%s' % zip_file_name
    return response

Everything is fine and all photos are made in zip file but there is only one problem. The problem is that the photos won't open and this error will appear in Windows:

Its look like we don't support this file format.

What is wrong with my codes?


Solution

  • To append data from file you have to use

    write(filename)

    Using writestr(filename) you add only string from variable filename but not from file.