Pylons在Windows上上传扭曲图像
我正在用Pylons创建一个网页应用,正在处理图片上传的功能。目前我在我的Windows电脑上用egg:paste#http运行这个应用,配置是按照Pylons文档中的快速入门指南设置的。
当我把一张图片通过POST方式发送到我的应用后,再把这张图片移动到网页根目录,然后在浏览器中打开上传的图片时,图片显示得很扭曲。我上传了一个雅虎logo的GIF图片,结果就是这样,但大多数文件在浏览器中根本不显示,可能是因为文件损坏了:
扭曲的雅虎logo http://www.freeimagehosting.net/uploads/d2c92aef00.png
这是我正在使用的基本代码(直接来自Pylons文档):
os_path = os.path.join(config.images_dir, request.POST['image'].filename)
save_file = open(os_path, 'w')
shutil.copyfileobj(request.POST['image'].file, save_file)
request.POST['image'].file.close()
save_file.close()
request.POST['image']是一个cgi.FieldStorage对象。我觉得这可能和Windows的换行符有关,但我不太确定怎么检查或者修正这个问题。是什么导致我上传的图片变得扭曲或损坏呢?
1 个回答
3
你可能只是缺少了'b'(二进制)这个标志,这样才能有效地将文件写入为二进制格式:
save_file = open(os_path, 'wb')
不过我不明白你为什么要在这里使用shutil.copyfileobj
这个调用,为什么不试试这样做:
file_save_path = os.path.join(config.images_dir, request.POST['image'].filename)
file_contents = request.POST['image'].file.read()
# insert sanity checks here...
save_file = open(file_save_path, 'wb')
save_file.write(file_contents)
save_file.close()
或者把最后三行代码写得更符合Python的风格(确保即使写入失败,文件也能正常关闭):
with open(file_save_path, 'wb') as save_file:
save_file.write(file_contents)
如果你使用的是Python 2.6以下的版本,可能需要在文件顶部加上一个
from __future__ import with_statements