python中要压缩的图像

2024-10-01 13:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在使用下面的代码,但它给了我一个curruptzip文件。。在

url = urllib2.urlopen('http://mattfarmer.net/projects/thickbox/images/plant4.jpg')
f = StringIO()
zip = zipfile.ZipFile(f, 'w')
zip.writestr('plant4.jpg', url.read())
response = HttpResponse(f.getvalue(), content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=plant4bar.zip'
return response

Tags: 文件代码httpurlnetresponseurllib2zip
1条回答
网友
1楼 · 发布于 2024-10-01 13:43:54

你应该关闭你的压缩文件

from django.http import HttpResponse
import urllib2
from StringIO import StringIO
import zipfile

def home(request):
    url = urllib2.urlopen('http://mattfarmer.net/projects/thickbox/images/plant4.jpg')
    f = StringIO()
    zip = zipfile.ZipFile(f, 'w')
    zip.writestr('plant4.jpg', url.read())
    zip.close() # Close
    response = HttpResponse(f.getvalue(), content_type="application/zip")
    response['Content-Disposition'] = 'attachment; filename=plant4bar.zip'
    return response

相关问题 更多 >