python - Pylons 在 Windows 上上传扭曲的图像

标签 python image file-upload pylons paster

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

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

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

最佳答案

您可能只是缺少用于有效地将文件写入二进制文件的“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,则位于文件顶部。

关于python - Pylons 在 Windows 上上传扭曲的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2113126/

相关文章:

html - 如何使用knitr导入本 map 片进行 Markdown

javascript - 使用 IMG SRC 作为链接 REF 将 LINK 动态添加到 IMG 标签

python - SQL炼金术? JSONB 键上的运算符

python - 无法使用 Python 截断数字

python - 根据是否选中 QCheckbox 获取表行值

linux - 如何对子文件夹中的所有图像使用 ImageMagick 转换命令

php - 文件未使用 html 输入类型文件上传

Java Spring MultipartFile 上传多个文件时 Controller 仅看到第一个文件

firefox - 如何在 Selenium 测试中使用firefoxdriver上传文件

python - 寻找相似的词