【问题标题】:Pylons Uploading Distorted Images on WindowsPylons 在 Windows 上上传扭曲的图像
【发布时间】:2010-01-21 21:38:37
【问题描述】:

我正在 Pylons 中创建一个网络应用程序,并且正在处理图像上传操作。这目前在我的 Windows 机器上使用 egg:paste#http 运行,在 pylons 文档快速入门中描述的基本开发配置中。

当我将图像发布到我的应用程序,然后将图像移动到 Web 根目录,然后在浏览器中拉出上传的图像时,图像出现失真。这是我上传 Yahoo! 的 GIF 时得到的。徽标,但大多数文件根本不显示在浏览器中,可能是因为损坏:

distorted yahoo 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 行结尾的问题,但我不确定如何检查或纠正它。是什么导致我上传的图片失真/损坏?

【问题讨论】:

  • “扭曲”是什么意思?
  • 在上面的帖子中添加了示例图片

标签: python image file-upload pylons paster


【解决方案1】:

您可能只是缺少 '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()

或者让最后三行更加 Pythonic(确保即使写入失败,文件句柄也会关闭):

with open(file_save_path, 'wb') as save_file:
    save_file.write(file_contents)

你可能需要一个

from __future__ import with_statements

如果您低于 Python 2.6,则位于文件顶部。

【讨论】:

  • Pylons 书中shutil.copyfileobj 的理由是避免将非常大的文件加载到内存中。我也相信.file.read()可以换成.value,但是我还在学习这个东西。
  • 哦,建议在使用前检查request.POST['image'].filename。
猜你喜欢
  • 2012-05-31
  • 2017-03-14
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
相关资源
最近更新 更多