如何在静态文件夹下压缩所有pdf文件? django的

时间:2017-07-16 02:11:02

标签: python django pdf zip compression

我在pdfs文件夹下有一个名为static的文件夹。

我正在尝试使用包含pdfs文件夹中所有pdf文件的返回zip。

我已经尝试了几个线程并使用了他们的代码,但我尝试了一些东西,但后来无法解决最后一部分,我收到的消息说没有文件/目录

我知道静态文件夹与普通文件夹有点不同。

有人可以帮我一把,看看我错过了什么吗?

提前致谢

    from StringIO import StringIO
    import zipfile

    pdf_list = os.listdir(pdf_path)
    print('###pdf list################################')
    print(pdf_path)  # this does show me the whole path up to the pdfs folder
    print(pdf_list)  # returns ['abc.pdf', 'efd.pdf']

    zip_subdir = "somefiles"
    zip_filename = "%s.zip" % zip_subdir

    # Open StringIO to grab in-memory ZIP contents
    s = StringIO()

    # Grab ZIP file from in-memory, make response with correct MIME-type
    resp = HttpResponse(content_type='application/zip')
    # ..and correct content-disposition
    resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename

    # The zip compressor
    zf = zipfile.ZipFile(s, "w")
    for pdf_file in pdf_list:
        print(pdf_file)

        zf.write(pdf_file, pdf_path + pdf_file)


    zf.writestr('file_name.zip', pdf_file.getvalue())
    zf.close()

    return resp

这里我因为无法找到'abc.pdf'

的文件/目录而遇到错误

P.S。我真的不需要将任何子文件夹压缩到zip文件中。只要所有文件都在zip中,它就会很好。 (pdfs文件夹中没有任何子文件夹)

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题并将其变成了一个带注释的函数。 我自己以前很复杂的事情

# two params
# 1. the directory where files want to be zipped
# e.g. of file directory is /et/ubuntu/vanfruits/vanfruits/static/pdfs/
# 2. filename of the zip file
def render_respond_zip(self, file_directory, zip_file_name):
    response = HttpResponse(content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=' + zip_file_name

    # open a file, writable
    zip = ZipFile(response, 'w')

    # loop through the directory provided
    for single_file in os.listdir(file_directory):
        # open the file, full path to the file including file name and extension is needed as first param
        f = open(file_directory + single_file, 'r')

        # write the file into the zip with
        # first param is the name of the file inside the zip
        # second param is read the file
        zip.writestr(single_file, f.read())

    zip.close()

    return response