"Error 0x80070057: The parameter is incorrect" 解压缩文件时

"Error 0x80070057: The parameter is incorrect" when unzipping files

我创建了一个函数来使用 Weasyprint 创建多个 PDF,将它们压缩在一起并下载 zip 文件。当尝试使用内部 zip 程序提取 Windows 10 上的文件夹时,出现此错误:

"An unexpected error is keeping you from copying the file. [...] Error 0x80070057" <

我可以跳过错误并提取文件。然而,在最好的情况下,我想防止这个错误。

def get_all_shareholder_reports(request):
   current_shareholders = list(models.objects.all())

    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, "a") as zip_file:

        for shareholder in current_shareholders:
            pdf_file_handle = io.BytesIO()
            context_dict = get_report_details(pk=shareholder.shareholder_id)

            html_string = render_to_string('template.html',
                                           context_dict)

            html_handler = HTML(string=html_string, base_url=request.build_absolute_uri())
            html_handler.write_pdf(target=pdf_file_handle)
            pdf_file_handle.seek(0)
            pdf_string = pdf_file_handle.getvalue()
            pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
                                                                     context_dict['shareholder'].surname,
                                                                     datetime.datetime.now().strftime(
                                                                         "%d_%m_%Y_%H:%M:%S"))
            zip_file.writestr(zinfo_or_arcname=pdf_file_name, data=pdf_string)

    zip_buffer.seek(0)
    response = HttpResponse(zip_buffer.getvalue(), content_type="application/x-zip-compressed")

    response['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip'

    return response

我想通了:zip 文件不喜欢文件名中的“:”。删除它们解决了问题。

pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
                                                                     context_dict['shareholder'].surname,
                                                                     datetime.datetime.now().strftime(
                                                                         "%d_%m_%Y_%H_%M_%S"))

您基本上需要清除 Windows 中所有保留字符的文件名:https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions

所以下面应该这样做"filename".replaceAll("[<>:\"/\\|?*]", "")