我使用Python中的requests库通过HTTP下载大量的图片文件。我使用BytesIO将接收到的内容转换为原始字节,然后使用Pillow()将这些原始内容保存为JPEG文件。
from PIL import Image
from io import BytesIO
rsp = requests.get(imageurl)
content_type_received = rsp.headers['Content-Type'] # mime type
binarycontent = BytesIO(rsp.content)
if content_type_received.startswith('image'): # image/jpeg, image/png etc
i = Image.open(binarycontent)
outfilename = os.path.join(outfolder,'myimg'+'.jpg')
with open(outfilename, 'wb') as f:
f.write(rsp.content)
rsp.close()
这段代码存在哪些潜在的安全风险?(我不确定我们能够相信服务器响应头中声明的 MIME 类型是否真的是服务器所说的类型)。有没有更好的方式来编写安全的下载程序?