在 Django 中打开存储在 zip 文件中的照片时出错

Error opening photos stored in zip file in Django

我将使用我服务器上存储的一些图像文件创建一个 zip 文件。 我使用以下函数来执行此操作:

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

一切都很好,所有照片都压缩成 zip 文件,但只有一个问题。 问题是照片打不开,这个错误会出现在Windows:

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

我的代码有什么问题?

要从文件追加数据,您必须使用

write(filename)

使用 writestr(filename) 您只添加来自变量 filename 的字符串,而不是来自文件的字符串。